如何从 main 获取退出代码 3 或除 1 以外的任何非零?我正在尝试执行一个程序,但是当我执行时将获得退出代码 1 而不是 3。如果我想获得退出代码 3,我需要做什么? 例如:
package main
import "os"
func main() {
// Exit with status code.
os.Exit(3)
}
我想通过 python 脚本运行 go 脚本 请在下面找到 python 脚本:
from subprocess import Popen, PIPE
def console(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
out, err = p.communicate()
return (p.returncode, out, err)
if __name__ == '__main__':
result = console('go build test.go')
result = console('./test')
result = console('echo $?')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]
我想在Python程序中记录退出状态码,可以进一步用于其他逻辑。
最佳答案
我猜你正在使用 go run
来执行。在这种情况下,退出状态不可用,因为您的可执行文件未在 bash 中运行,run
正在子进程中执行它。要查看差异,请使用 build
并执行它们,
示例
$ go build test.go
$ ./test
$ echo $?
3
编辑
如果您使用的是 Python 程序,则无需运行 echo $?
。这会给你一个错误的答案,因为这是在不同于执行 ./test
命令的 shell 中执行的。
您始终可以从 Popen.returncode
中读取命令的退出状态。脚本可以修改为
from subprocess import Popen, PIPE
def console(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
out, err = p.communicate()
return (p.returncode, out, err)
if __name__ == '__main__':
result = console('./test')
print result
这会给
$ python test.py
(3, '', None)
关于python - 如何从 go 语言的 main 中获取不同的退出代码,如 2 或 3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46400038/