Golang中的 'exec.Command' 如何处理单引号参数?
时间:2024-02-07
浏览:183
作者:佚名
大家好,我们又见面了啊~本文《Golang中的 'exec.Command' 如何处理单引号参数?》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~
问题内容
我参考帖子如何使用未知参数执行系统命令?在我的 ubuntu shell 上运行 jq 命令。 下面是我尝试过的代码
import (
"fmt"
"os/exec"
"sync"
"strings"
)
func execmd(cmd string, wg *sync.waitgroup) {
fmt.println("command is ",cmd)
// splitting head => g++ parts => rest of the command
parts := strings.fields(cmd)
head := parts[0]
parts = parts[1:len(parts)]
out, err := exec.command(head,parts...).output()
if err != nil {
fmt.printf("%s", err)
}
fmt.printf("%s", out)
wg.done() // need to signal to waitgroup that this goroutine is done
}
func main() {
wg := new(sync.waitgroup)
wg.add(1)
x := []string{"jq '(.data.legacycollection.collectionspage.stream.edges|map({node:(.node|{url,firstpublished,headline:{default:.headline.default},summary})})) as $edges|{data:{legacycollection:{collectionspage:{stream:{$edges}}}}}' long-response.json > short-response.json"}
execmd(x[0], wg)
wg.wait()
}
输出如下,似乎命令被正确检测到,但 shell 返回退出状态 3,即“没有这样的进程”?
command is jq '(.data.legacyCollection.collectionsPage.stream.edges|map({node:(.node|{url,firstPublished,headline:{default:.headline.default},summary})})) as $edges|{data:{legacyCollection:{collectionsPage:{stream:{$edges}}}}}' long-response.json > short-repsonse.json exit status 3
有人可以帮忙解决这个问题吗? 我想要的是一个 go 函数,它可以像在 linux shell 上一样包装和运行 bash 命令行 ps:当我将上面的 jq 命令粘贴到 linux shell 上时,我尝试的效果非常好
尝试了其他方法:删除了我的 jq 命令中的单引号,并且我的命令以我期望的输出执行 - 一个已解析的 json 文件 但我仍然得到了存在状态 2 ,任何人都可以解释
- 为什么命令行中的单引号会影响 g 解析命令的方式?
- 为什么我的 shell 命令完成后仍然会存在 2?
正确答案
该程序执行 jq 命令,而不是 shell。 jq 命令不理解传递给该命令的 shell 语法(引号和 i/o 重定向)。
使用以下代码运行命令,并将 stdout 重定向到 short-response.json。
cmd := exec.Command("jq",
"(.data.legacyCollection.collectionsPage.stream.edges|map({node:(.node|{url,firstPublished,headline:{default:.headline.default},summary})})) as $edges|{data:{legacyCollection:{collectionsPage:{stream:{$edges}}}}}",
"long-response.json")
f, err := os.Create("short-response.json")
if err != nil {
log.Fatal(err)
}
defer f.Close()
cmd.Stdout = f // set stdout to short-response.json
err = cmd.Run()
if err != nil {
log.Fatal(err)
}到这里,我们也就讲完了《Golang中的 'exec.Command' 如何处理单引号参数?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.30
11.30
11.30
11.30
11.30
热门专题
