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

I run a python script that create a PNG file using the exec package:

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

How could I safely check the command exit state and that the PNG file was successfully created ?

Simply checking the return from cmd.Run() will do, if the program returned any error or didn't exit with status 0, it will return that error.

if err := cmd.Run(); err != nil {
    panic(err)
}

Checking the error returned by cmd.Run() will let you know if the program failed or not, but it's often useful to get the exit status of the process for numerical comparison without parsing the error string.

This isn't cross-platform (requires the syscall package), but I thought I would document it here because it can be difficult to figure out for someone new to Go.

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
", waitStatus.ExitStatus())
        }
    }
}