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.
Best Solution
In Python 2.7 or Python 3
Instead of making a
Popen
object directly, you can use thesubprocess.check_output()
function to store output of a command in a string:In Python 2.4-2.6
Use the
communicate
method.out
is what you want.Important note about the other answers
Note how I passed in the command. The
"ntpq -p"
example brings up another matter. SincePopen
does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"]
.