doc:appunti:prog:python_program_execution
This is an old revision of the document!
−Table of Contents
Program execution from Python
The right module to use is subprocess. Older modules and functions that should be avoided are:
- os.system
- os.spawn*
- os.popen*
- popen2.*
- commands.*
Run a command
Run command with arguments. Wait for command to complete, then return the returncode attribute.
retcode = subprocess.call(["mycmd", "myarg"])
Same as above, but run in a subshell:
retcode = call("mycmd myarg", shell=True)
Get the output of a program
Assign the output to a variable:
output = subprocess.Popen(["mycmd", "myarg"], stdout=subprocess.PIPE).communicate()[0]
Get also the return code and iterate on the output:
subproc = subprocess.Popen(["mycmd", "myarg"], stdin=None, stdout=subprocess.PIPE) output = subproc.communicate()[0] retcode = subproc.returncode for line in output.splitlines(): print line
Redirect output to a file
file = open("/tmp/cmd_output", "w") subprocess.call(["mycmd", "myarg"], stdout=file) file.close()
doc/appunti/prog/python_program_execution.1288070662.txt.gz · Last modified: 2010/10/26 07:24 by niccolo