Skip to content

Instantly share code, notes, and snippets.

@jmquintana79
Last active January 5, 2020 22:01
Show Gist options
  • Save jmquintana79/20af0a4a094204e2d1c3 to your computer and use it in GitHub Desktop.
Save jmquintana79/20af0a4a094204e2d1c3 to your computer and use it in GitHub Desktop.
run bash command in python
## RUN BASH COMMAND IN PYTHON
import subprocess
scommand = './script.sh'
_ = subprocess.call(scommand, shell=True)
## RUN BASH COMMAND IN PYTHON with error control
from subprocess import run, PIPE
result = run("./script.sh", stdout=PIPE, stderr=PIPE, universal_newlines=True) # universal_newline: stdout/stderr strings with or without newline (str or byte)
print('returncode: %s\nstdout: %s\nstderr: %s'%(result.returncode, result.stdout, result.stderr))
## VERSION 1: LAUNCH COMMAND
def run_command(sbashCommand):
import subprocess
try:
# launch bash command and get output
p = subprocess.Popen(sbashCommand.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
# byte to string
out = out.decode("utf-8")
err = err.decode("utf-8")
# return
return [out, err]
except Exception as e:
return [None,str(e)]
## VERSION 2: LAUNCH COMMAND
def run_command(sbashCommand):
import subprocess
try:
return subprocess.check_output(['bash','-c', sbashCommand])
except Exception as e:
print(str(e))
return None
if __name__ == "__main__":
# execute bash command
out, err = run_command("ls")
# screen output
lresult = [i for i in run_command("ls %s"%path_input).decode("utf-8").split('\n') if len(i)>0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment