Home >Backend Development >Python Tutorial >How Can I Retrieve the Output of a Subprocess in Python?
When invoking subprocesses using subprocess.call(), it can be challenging to access the output generated by the called process. This article addresses this issue and provides a solution.
Traditionally, attempting to capture output using a StringIO.StringIO object, as shown below, would lead to an error:
import StringIO ... stdout = StringIO.StringIO() ... subprocess.call(...)
This error occurs because StringIO objects lack the fileno() method required by subprocess.call().
To circumvent this limitation, Python 2.7 and subsequent versions introduced the subprocess.check_output function. This function efficiently captures the standard output of a subprocess and returns it as a string.
Here's a simple example demonstrating the usage of subprocess.check_output() in Linux:
import subprocess output = subprocess.check_output(["ping", "-c", "1", "8.8.8.8"]) print(output)
Note that the Linux ping command uses "-c" to specify the number of packets to send, while Windows uses "-n" for the same purpose.
For an in-depth explanation and additional use cases, refer to the following Stack Overflow answer:
[How to run a command and get the output in Python?](https://stackoverflow.com/questions/1365265/how-to-run-a-command-and-get-the-output-in-python)
The above is the detailed content of How Can I Retrieve the Output of a Subprocess in Python?. For more information, please follow other related articles on the PHP Chinese website!