Skip to content

Instantly share code, notes, and snippets.

@simonrad
Last active August 23, 2017 01:20
Show Gist options
  • Select an option

  • Save simonrad/3198324b57594c98d3ce25e4cdee6079 to your computer and use it in GitHub Desktop.

Select an option

Save simonrad/3198324b57594c98d3ce25e4cdee6079 to your computer and use it in GitHub Desktop.
Helper function to easily run a bash command and get its output
import subprocess
def run_bash_command(command):
'''
Returns the stdout of the command.
If the exit code is non-zero, raises a subprocess.CalledProcessError.
Note: If the command involves ssh, it's recommended that you pass the -T option to ssh, to prevent it from messing with your terminal modes.
'''
return subprocess.check_output(['bash', '-c', command]).strip()
# --------------------
# Example usage below:
# --------------------
get_num_files_cmd = "ls -l | grep -v '^total' | grep -v '^d' | wc -l"
num_files = int(run_bash_command(get_num_files_cmd))
pwd = run_bash_command("pwd")
print 'There are %d files in the current directory' % (num_files,)
print 'The current directory is %r' % (pwd,)
try:
run_bash_command("wtf_is_this")
except subprocess.CalledProcessError:
print 'Exception thrown as expected (this is good).'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment