Thursday, October 25, 2012

spawn a process and get the output with python

The simplest way to spawn a process is to use os.system(COMMAND), however if you want to intercept the output, you need to python's process module.
from subprocess import *

cmd = ["ls", "-alF"]

p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)

stdout,stderr = p.communicate()
print stdout
You need PIPE assigned to stdin/stdout/stderr in order to get the result assigned to local variables.

With close_fds value as True, all the file descriptors in the process is closed. You can just remove this option. If you have a long command line string, then you can use STRING.split() method to get a list to an input to Popen method.


No comments:

Post a Comment