Skip to content

Instantly share code, notes, and snippets.

@colehocking
Created December 2, 2020 18:20
Show Gist options
  • Save colehocking/6fe90545114c15978285fbd3a6b60608 to your computer and use it in GitHub Desktop.
Save colehocking/6fe90545114c15978285fbd3a6b60608 to your computer and use it in GitHub Desktop.
Run a bash subprocess in Python -- the ideal way
def run_script(script, stdin=None):
"""Returns (stdout, stderr), raises error on non-zero return code"""
import subprocess
# Note: by using a list here (['bash', ...]) you avoid quoting issues, as the
# arguments are passed in exactly this order (spaces, quotes, and newlines won't
# cause problems):
proc = subprocess.Popen(['bash', '-c', script],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode:
raise ScriptException(proc.returncode, stdout, stderr, script)
return stdout, stderr
class ScriptException(Exception):
def __init__(self, returncode, stdout, stderr, script):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
Exception.__init__('Error in script')
@colehocking
Copy link
Author

colehocking commented Dec 2, 2020

import os
script = """
echo $0
ls -l
echo done
"""
os.system("bash -c '%s'" % script)
the simple way

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment