英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论