Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run external python script and check exit status

Tags:

go

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 ?


2 Answers

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())
        }
    }
}
like image 170
JimB Avatar answered May 12 '26 10:05

JimB


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)
}
like image 34
OneOfOne Avatar answered May 12 '26 10:05

OneOfOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!