Getting shell output with Python?
subprocess.call()
does not give you the output, only the return code. For the output you should use subprocess.check_output()
instead. These are friendly wrappers around the popen family of functions, which you could also use directly.
For more details, see: http://docs.python.org/library/subprocess.html
Manually using stdin and stdout with Popen was such a common pattern that it has been abstracted into a very useful method in the subprocess module: communicate
Example:
p = subprocess.Popen(['myscript', 'www.google.com'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)(stdoutdata, stderrdata) = p.communicate(input="myinputstring")# all done!
import subprocess as spp = sp.Popen(["/usr/bin/svn", "update"], stdin=sp.PIPE, stdout=sp.PIPE, close_fds=True)(stdout, stdin) = (p.stdout, p.stdin)data = stdout.readline()while data: # Do stuff with data, linewise. data = stdout.readline()stdout.close()stdin.close()
Is the idiom I use, obviously in this case I was updating an svn repository.