Home >Backend Development >Python Tutorial >How Can I Efficiently Capture and Store the Output of a subprocess.Popen Call in Python?
Storing Output of subprocess.Popen Call in a String
When attempting to make a system call using Python, it can be necessary to store the output for later manipulation. However, using subprocess.Popen alone does not provide a straightforward method for capturing the output within a string.
Alternative Approaches
To address this issue, consider the following options:
Python 2.7 or Python 3
Utilize the subprocess.check_output() function, which simplifies command execution and output capture:
from subprocess import check_output out = check_output(["ntpq", "-p"])
Python 2.4-2.6
Employ the communicate method of the Popen object:
import subprocess p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE) out, err = p.communicate()
In this case, out will contain the desired output.
Note on Command Invocation
When using Popen, specify the command as a list containing the command and options, e.g., ["ntpq", "-p"]. This ensures the command is interpreted correctly, as Popen does not utilize the shell for command execution.
The above is the detailed content of How Can I Efficiently Capture and Store the Output of a subprocess.Popen Call in Python?. For more information, please follow other related articles on the PHP Chinese website!