Reputation:
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 ?
Upvotes: 3
Views: 1585
Reputation: 109443
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\n", waitStatus.ExitStatus())
}
}
}
Upvotes: 6