Home > Software engineering >  Portable way to check if subprocess exit code indicates a success?
Portable way to check if subprocess exit code indicates a success?

Time:06-22

I'm looking for a portable way to check whether a subprocess exited with an exit code indicating a success.

I found out that some systems don't follow the standard convention of 0 meaning "success" (e.g. OpenVMS) so the solution isn't as trivial as just process.returncode == 0.

CodePudding user response:

The docs for subprocess effectively require that 0 means success, e.g. for subprocess.run (the all-in-one high level synchronous API), when check=True, the docs specify:

If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised.

OpenVMS isn't actually a supported target for CPython, and all supported targets obey that rule to my knowledge.

Presumably the third-party OpenVMS port would have to include porting proper error-checking (even if it doesn't change the exit codes, check=True should be changed to make it only raise the exception when the child fails). So the simplest solution would be to write your code as:

try:
    proc = subprocess.run(..., check=True)
except subprocess.CalledProcessError:
    # Handle failure here

and if OpenVMS didn't make check=True work the logically correct way in their port, file a bug against them to make it logically match the intended behavior (exception raised when subprocess fails, even if docs say "non-zero"). Aside from that, your only option is checking sys.platform and manually checking the error code a different way on OpenVMS (I have no idea what OpenVMS reports for sys.platform, you'd have to check it yourself).

  • Related