Table of Content

There are so many ways to run shell command in python, and we run shell command all the time, lazy to place those subprocess calls everywhere, so it is necessary to have wrapper for it.

This is most powerful and easy one I used, take over everything from subprocess but hide the details.

Please remember return is tuple (out,err).

#!/usr/bin/python
# run_shell
# @dreamcloud
# Latest update: Aug 5, 2015

import subprocess
import shlex

def run_shell(shell_cmd):
    """
    @dreamcloud
    run unix shell command, it is wrapper of subprocess
    return (out,err)
    """
    proc=subprocess.Popen(shlex.split(shell_cmd),stdout=subprocess.PIPE, bufsize=4096)
    out,err = proc.communicate()
    return out,err

if __name__ == '__main__':

    cmd='ls -ltr'
    out,err=run_shell(cmd)
    print out