Python 2: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
from subprocess import PIPE, Popen
command = "ntpq -p"
process = Popen(command, stdout=PIPE, stderr=None, shell=True)
output = process.communicate()[0]
print output
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:
command = ["ntpq", "-p"]
process = Popen(command, stdout=PIPE, stderr=None)
If you need to read also the standard error, into the Popen initialization, you should set stderr to PIPE or STDOUT:
command = "ntpq -p"
process = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
output, error = process.communicate()
NOTE: Starting from Python 2.7, you could/should take advantage of subprocess.check_output (https://docs.python.org/2/library/subprocess.html#subprocess.check_output).
Python 3: https://docs.python.org/3/library/subprocess.html#subprocess.Popen
from subprocess import PIPE, STDOUT, Popen
command = "ntpq -p"
with Popen(command, stdout=PIPE, stderr=STDOUT, shell=True) as process:
output = process.communicate()[0].decode("utf-8")
print(output)
If besides storing the output, you want to print it "live" as this is produced (i.e., without waiting the command run to complete - e.g., for debugging purposes if this is taking several seconds/minutes), you can take advantage of Popen.poll():
output = ""
error = ""
command = ["ntpq", "-p"]
with Popen(command, stdout=PIPE, stderr=PIPE, text=True) as process:
while process.poll() is None:
stdout = process.stdout.readline()
print(stdout.strip())
output += stdout
stderr = process.stderr.readline()
print(stderr.strip())
error += stderr
NOTE: If you're targeting only versions of Python higher or equal than 3.5, then you could/should take advantage of subprocess.run (https://docs.python.org/3/library/subprocess.html#subprocess.run).
from subprocess import run
command = ["ntpq", "-p"]
output = run(command, check=True, capture_output=True, text=True)
if output.stdout is not None and output.stdout != "":
print(output.stdout)
if output.stderr is not None and output.stderr != "":
print(output.stderr)
"ntpq -p", which is a different part of the problem than you're asking about.