Storing Output of subprocess.Popen Call in a String
In Python programming, using the subprocess module allows you to execute system calls and capture their output. This article provides solutions for storing the output of a subprocess.Popen call in a string variable.
Solution for Python 2.7 or Python 3
Python provides the subprocess.check_output() function, specifically designed for capturing the output of a command into a string. Simply use it as follows:
from subprocess import check_output out = check_output(["ntpq", "-p"])
Solution for Python 2.4-2.6
For Python versions 2.4 to 2.6, you can utilize the communicate method of Popen:
import subprocess p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE) out, err = p.communicate()
The out variable in the above code contains the desired output.
Note Regarding Command Input
When utilizing Popen, it's crucial to pass the command as a list of strings, as shown in the examples provided. This is because Popen does not invoke the shell.
The above is the detailed content of How Can I Capture and Store the Output of a subprocess.Popen Call as a String in Python?. For more information, please follow other related articles on the PHP Chinese website!