The attached patch introduces a 3rd utility function -
xcall() to the
subprocess module. This function acts just like call
but raises
errors if the command had a non-zero return code.
This saves writing
if call(...):
raise OSError(...)
It is most useful for shell script replacement
programming. Checking
the return codes of commands called is often forgotten
in shell
programming.
When you've moved up to python because shell is too
limiting (usually
about 10 lines of shell in my case ;-) you want to make
sure that all
your commands work so you write robust code.
I consider raising an exception to be much more
pythonic than checking
a return code (ie "Errors should never pass silently"
from Zen of
Python)
Eg
# An easy to miss error
>>> subprocess.call(["mkdir", "a/b"])
mkdir: cannot create directory `a/b': No such file or
directory
1
>>> # user forgot to check non-zero return code
# becomes an impossible to miss exception
>>> subprocess.xcall(["mkdir", "a/b"])
mkdir: cannot create directory `a/b': No such file or
directory
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "subprocess.py", line 462, in xcall
raise CalledProcessError(rc, "Command %s returned
non zero exit status" % args[0])
subprocess.CalledProcessError: [Errno 1] Command
['mkdir', 'a/b'] returned non zero exit status
>>>
See attached patch for more! Its been tested under
python 2.3 on
windows and linux.
|