Created
July 11, 2011 22:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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