运行外部python脚本并检查退出状态

时间:2014-06-30 20:08:52

标签: go

我运行一个使用exec包创建PNG文件的python脚本:

cmd := exec.Command("python", "script.py")
cmd.Run()

如何安全地检查命令退出状态以及PNG文件是否已成功创建?

2 个答案:

答案 0 :(得分:6)

检查cmd.Run()返回的错误会告诉您程序是否失败,但是在不解析错误字符串的情况下获取数字比较过程的退出状态通常很有用。

这不是跨平台的(需要syscall包),但我想我会在这里记录它,因为很难找到新来的人。

if err := cmd.Run(); err != nil {
    // Run has some sort of error

    if exitErr, ok := err.(*exec.ExitError); ok {
        // the err was an exec.ExitError, which embeds an *os.ProcessState.
        // We can now call Sys() to get the system dependent exit information.
        // On unix systems, this is a syscall.WaitStatus.

        if waitStatus, ok := exitErr.Sys().(syscall.WaitStatus); ok {
            // and now we can finally get the real exit status integer
            fmt.Printf("program exited with status %d\n", waitStatus.ExitStatus())
        }
    }
}

答案 1 :(得分:4)

只需检查cmd.Run()的返回即可,如果程序返回任何错误或未以状态0退出,则会返回该错误。

if err := cmd.Run(); err != nil {
    panic(err)
}
相关问题