0
output = subprocess.check_call('invented_command', shell=True)  # Returns 127

This code raise an exception (as explained in the manual) with 127 instead of assign 127 to the "output" variable, which remains unassigned. Only if the exit code is equal to 0, the "output" variable is set.

Mario Palumbo
  • 693
  • 8
  • 32

1 Answers1

1

The very definition of check_call is that it will raise an exception if the call fails; that's what the check part checks.

Its sibling subprocess.call(), without the check, does exactly what you are asking for, though, and returns the result code directly, and is available all the way back to Python 2.4 (which is when subprocess was introduced).

With Python 3.5+ you can replace check_call and call (as well as check_output) with run with suitable parameters. For this specific case it's slightly more complicated, but if you need anything more than just the basics, it's a better and more versatile starting point for writing a wrapper of your own.

result = subprocess.run(['invented_command'])  # check=True to enable check
status_code = result.returncode

Notice also how I changed the wrapper to avoid shell=True which seemed superfluous here; if your actual invented command really requires a shell for some reason, obviously take out the [...] around the command and add back the pesky shell=True (or, better yet, find a way to avoid it by other means).

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    For (much) more, check out https://stackoverflow.com/questions/4256107/running-bash-commands-in-python/51950538#51950538 – tripleee Feb 04 '21 at 11:32
  • I have read the magnific explanation, consequently, can you see this other question? https://stackoverflow.com/questions/65952314 This question is not a duplicate as claimed by users, and it is self-evident. – Mario Palumbo Feb 04 '21 at 13:28
  • I was already active on that question; Python cannot know which output comes from which one of multiple shell commands if they are all invoked as a single subprocess. – tripleee Feb 04 '21 at 13:32
  • Not even with the shell still running (using Popen)? – Mario Palumbo Feb 04 '21 at 14:03
  • 1
    How could you know if the output you received came from two commands `echo "foo"; echo "bar"` or a single one `printf '%s\n' "foo" "bar"`? (Other than possibly creating your own process monitor and your subprocess as a child of that.) – tripleee Feb 04 '21 at 14:08