Capturing Subprocess Output in a String
To capture the output of a system call initiated through Python's subprocess.Popen and store it in a string, Python provides several options depending on the version you're using.
Python 2.7 or Python 3:
Leverage the subprocess.check_output() function:
from subprocess import check_output output = check_output(["ntpq", "-p"])
Python 2.4-2.6:
Employ the Popen command's communicate method:
import subprocess process = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE) output, _ = process.communicate()
Note that when specifying the command, separate the executable and options into a list, such as ["ntpq", "-p"], as Popen does not invoke a shell.
The above is the detailed content of How Can I Capture Subprocess Output as a String in Python?. For more information, please follow other related articles on the PHP Chinese website!