Home >Backend Development >Python Tutorial >How Can I Retrieve the Output of a Subprocess in Python?

How Can I Retrieve the Output of a Subprocess in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 17:40:15818browse

How Can I Retrieve the Output of a Subprocess in Python?

Retrieving Output from Subprocesses

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.

Overcoming the Output Retrieval Challenge

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().

The Solution: subprocess.check_output()

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.

Further Explanation and Use Cases

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn