I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")
I've tried a few things including some of the suggestions here:
Retrieving the output of subprocess.call()
but without any luck.
I wrote a little function based on the other answers here:
Usage:
In this case you will only have one element in the list.
subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:
If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:
This was perfect for me. You will get the return code, stdout and stderr in a tuple.
For Example:
This worked for me for redirecting stdout (stderr can be handled similarly):
If it doesn't work for you, please specify exactly the problem you're having.
Assuming that
pwd
is just an example, this is how you can do it:See the subprocess documentation for another example and more information.