jmquintana79
11/12/2015 - 4:51 AM

run bash command

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]