Skip to content

Instantly share code, notes, and snippets.

@xiongchiamiov
Created July 11, 2011 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiongchiamiov/1076924 to your computer and use it in GitHub Desktop.
Save xiongchiamiov/1076924 to your computer and use it in GitHub Desktop.
Run `command` through the shell and return a tuple of the return code and the output.
from subprocess import PIPE, Popen, STDOUT
class ShellError(Exception):
def __init__(self, command, returnCode, output):
self.command = command
self.returnCode = returnCode
self.output = output
def __str__(self):
return '''Command '%s' exited with non-zero exit code %s.
Output:
%s ''' % (self.command, self.returnCode, self.output)
def shell(command, expectedReturnCode=0):
r'''
Run `command` through the shell and return a tuple of the return code
and the output.
>>> shell('uname -s')
(0, 'Linux\n')
>>> shell('ld -f')
Traceback (most recent call last):
...
ShellError: Command 'ld -f' exited with non-zero exit code 1.
Output:
ld: unrecognized option '-f'
ld: use the --help option for usage information
<BLANKLINE>
>>> shell('ld -f', 1)
(1, "ld: unrecognized option '-f'\nld: use the --help option for usage information\n")
'''
p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
output = p.communicate()[0]
if p.returncode != expectedReturnCode:
raise ShellError(command, p.returncode, output)
return (p.returncode, output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment