user2671513
user2671513

Reputation:

Run external python script and check exit status

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

Answers (2)

Mr_Pink
Mr_Pink

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

OneOfOne
OneOfOne

Reputation: 99381

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)
}

Upvotes: 4

Related Questions