Created
November 27, 2012 06:49
-
-
Save christopherhesse/4152797 to your computer and use it in GitHub Desktop.
Python function for running a shell command
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
def run(command_str, ignore_errors=False, **kwargs): | |
""" | |
Run the given command and return the output. Any keyword arguments provided | |
will be formatted into the command string. Quoting arguments should not be | |
necessary. | |
Example: | |
run('rm {file}', file='test file') | |
=> rm "test file" | |
run('rm "test file"') | |
=> same as previous, but you may have to worry more about escaping | |
run('ping -c {count} {host}', host='www.google.com', count=4) | |
=> ping -c 4 www.google.com | |
If ignore_errors is False (the default) then an exception will be raised if | |
the exit code of the command is non-zero. | |
If you want a literal '{' to appear in the command, use '{{' instead. | |
Same for '}' | |
""" | |
command_parts = shlex.split(command_str) | |
for index, part in enumerate(command_parts): | |
command_parts[index] = part.format(**kwargs) | |
try: | |
return subprocess.check_output(command_parts) | |
except subprocess.CalledProcessError: | |
if ignore_errors: | |
return None | |
else: | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment