想要使用Go程序运行带有标志和参数的二进制文件。

huangapple go评论82阅读模式
英文:

Want to run a binary having flags and arguments by using Go program

问题

我想运行一个带有标志的二进制文件。
如果我直接运行二进制文件,就像在一个 Golang 程序中一样。

./test --flag1 arg1 --flag2 arg2

我试图通过使用 os.exec 来运行。

代码:reslt, err := exec.Command("./test", "--flag1", "arg1", "--flag2", "arg2").Output

它报错了:

> 退出状态 2

有人可以帮忙吗?

英文:

I want to run a binary file with flags.
If i directly run the binary it will be like following inside a golang program.

./test --flag1 arg1 --flag2 arg2

I was trying to run by the use of os.exec.

code: reslt ,err:= exec.Command("./test","--flag1", "arg1", "--flag2", "arg2").Output

It is giving error:

> Exit status 2

Can anyone help on this?

答案1

得分: 1

output, err := exec.Command("./test", "flag1", "arg1", "flag2", "arg2").Output()

Output 返回一个字节切片和一个错误。根据错误提示,你只期望一个返回值,而 Output 返回两个。

编辑:至于调试你的第二个问题,可以从命令中获取 stderr

cmd := exec.Command("./test", "flag1", "arg1", "flag2", "arg2")
var stderr bytes.Buffer
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
    fmt.Println(stderr.String())
    return
}
英文:

output, err := exec.Command("./test","flag1", "arg1", "flag2", "arg2").Output()

Output returns both a slice of bytes and an error. As indicated by the error, you are only expecting a single return value, whereas Output returns two.

EDIT: As for debugging your second problem, get the stderr from the command:

cmd := exec.Command("./test","flag1", "arg1", "flag2", "arg2")
var stderr bytes.Buffer
cmd.Stderr = &stderr  
err := cmd.Run()
if err != nil {
    fmt.Println(stderr.String())
    return
}

答案2

得分: 0

我猜退出代码2意味着“没有这样的文件或目录”。你应该检查执行go二进制文件的路径和测试文件所在的路径。

请尝试首先指定绝对路径来运行你的命令。

英文:

I guess Exit code 2 means 'no such a file or directory'. You should check path where you executed go binary and where test is.

Please try to specify absolute path for your cimmand first.

huangapple
  • 本文由 发表于 2017年3月20日 17:31:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/42899981.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定