Home > Backend Development > Python Tutorial > How Can I Retrieve Process Output from `subprocess.call()` in Python?

How Can I Retrieve Process Output from `subprocess.call()` in Python?

Barbara Streisand
Release: 2024-11-30 04:26:17
Original
111 people have browsed it

How Can I Retrieve Process Output from `subprocess.call()` in Python?

Retrieving Process Output from subprocess.call()

In Python versions prior to 2.7, obtaining the output from a process invoked using subprocess.call() can be challenging. Passing a StringIO.StringIO object to the stdout argument triggers an error due to the lack of a 'fileno' attribute in StringIO objects.

Solution

For Python versions 2.7 and above, the subprocess.check_output function provides a straightforward solution. It combines the execution of a subprocess with the capture and return of its standard output as a string.

For example (tested on Linux):

import subprocess

output = subprocess.check_output(['ping', '-c', '1', '8.8.8.8'])

print(output)
Copy after login

Note that the ping command uses the Linux notation (-c for count). For Windows, change it to -n.

For further details, refer to the more comprehensive answer in this [other post](https://stackoverflow.com/a/5647266/6214952).

The above is the detailed content of How Can I Retrieve Process Output from `subprocess.call()` in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template