How to start a command line command from Python [duplicate] How to start a command line command from Python [duplicate] linux linux

How to start a command line command from Python [duplicate]


With subprocess one can conveniently perform command-line commands and retrieve the output or whether an error occurred:

import subprocessdef external_command(cmd):     process = subprocess.Popen(cmd.split(' '),                           stdout=subprocess.PIPE,                            stderr=subprocess.PIPE)    # wait for the process to terminate    out, err = process.communicate()    errcode = process.returncode    return errcode, out, err

Example:

print external_command('ls -l')

It should be no problem to rearrange the return values.


Use subprocess.

Example:

>>> subprocess.call(["ls", "-l"])0>>> subprocess.call("exit 1", shell=True)1