Created
December 2, 2020 18:20
-
-
Save colehocking/6fe90545114c15978285fbd3a6b60608 to your computer and use it in GitHub Desktop.
Run a bash subprocess in Python -- the ideal way
This file contains hidden or 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_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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
import os
script = """
echo $0
ls -l
echo done
"""
os.system("bash -c '%s'" % script)
the simple way