diff options
author | Julien Jehannet <julien.jehannet@logilab.fr> | 2008-11-21 17:09:17 +0100 |
---|---|---|
committer | Julien Jehannet <julien.jehannet@logilab.fr> | 2008-11-21 17:09:17 +0100 |
commit | 4a38052f001223afc25a8695a0392996300134ff (patch) | |
tree | 13732bdd5622ed80a55bd9927250f5487b5bfeaa /compat.py | |
parent | e636450f9123d7c328f79cc1a12be22c6ba67725 (diff) | |
download | logilab-common-4a38052f001223afc25a8695a0392996300134ff.tar.gz |
Python2.5 subprocess added functions and exceptions (call() + check_call())
Diffstat (limited to 'compat.py')
-rw-r--r-- | compat.py | 48 |
1 files changed, 48 insertions, 0 deletions
@@ -9,6 +9,7 @@ from __future__ import generators __docformat__ = "restructuredtext en" +import os from warnings import warn import __builtin__ @@ -241,3 +242,50 @@ except NameError: if not elt: return False return True + +# Python2.5 subprocess added functions and exceptions +from subprocess import Popen +class CalledProcessError(Exception): + """This exception is raised when a process run by check_call() returns + a non-zero exit status. The exit status will be stored in the + returncode attribute.""" + def __init__(self, returncode, cmd): + self.returncode = returncode + self.cmd = cmd + def __str__(self): + return "Command '%s' returned non-zero exit status %d" % (self.cmd, +self.returncode) + +def call(*popenargs, **kwargs): + """Run command with arguments. Wait for command to complete, then + return the returncode attribute. + + The arguments are the same as for the Popen constructor. Example: + + retcode = call(["ls", "-l"]) + """ + # workaround: subprocess.Popen(cmd, stdout=sys.stdout) fails + # see http://bugs.python.org/issue1531862 + if "stdout" in kwargs: + fileno = kwargs.get("stdout").fileno() + del kwargs['stdout'] + return Popen(stdout=os.dup(fileno), *popenargs, **kwargs).wait() + return Popen(*popenargs, **kwargs).wait() + +def check_call(*popenargs, **kwargs): + """Run command with arguments. Wait for command to complete. If + the exit code was zero then return, otherwise raise + CalledProcessError. The CalledProcessError object will have the + return code in the returncode attribute. + + The arguments are the same as for the Popen constructor. Example: + + check_call(["ls", "-l"]) + """ + retcode = call(*popenargs, **kwargs) + cmd = kwargs.get("args") + if cmd is None: + cmd = popenargs[0] + if retcode: + raise CalledProcessError(retcode, cmd) + return retcode |