4 ms·
On "Calling Other Programs with subprocess": It pains me that the default way to run an external command (subprocess.run) doesn't raise an exception for non-zer
by d0mine 5y ago
On "Calling Other Programs with subprocess": It pains me that the default way to run an external command (subprocess.run) doesn't raise an exception for non-zero exit code violating the Zen of Python: "Errors should never pass silently.
Unless explicitly silenced."
Would it make it too advanced to show subprocess.Popen example with stdin=PIPE for providing input instead of writing to disk? Or an example on how to force timeout for a command that might spawn its own child processes (send signal to a process group).
- jnwatson 5y agoJust pass check=True as an argument to subprocess.run and it will raise a CalledProcessError.
- d0mine 5y agoThe issue is that `check=False` by default for the `run()` function.
- dmuller 5y agoYeah - I agree, I don't like the default behavior of subprocess.run either. As another commenter pointed out, passing the check=True argument makes subprocess.run raise an Exception if the underlying command doesn't return 0 (would have been nice if this was the default). Those are two good use cases (using the lower level subprocess.Popen + process group signaling) that the book does not cover---thanks for bringing them up.
- auxym 5y agoNonzero exit as an error is only a convention, no? I've definitely used CLI programs in the past that used nonzero codes to report all sorts of non-error statuses.
- dijit 5y agoIt's more than convention though. if you run those commands in bash with `set -e` then the script will exit early when a command exits non-zero. I often run: `set -euo noglob -o pipefail` which is a way of preventing cascading catastrophes with bash scripts.