Home > Backend Development > Python Tutorial > How Can I Capture Subprocess Output as a String in Python?

How Can I Capture Subprocess Output as a String in Python?

Susan Sarandon
Release: 2024-12-02 21:27:12
Original
1037 people have browsed it

How Can I Capture Subprocess Output as a String in Python?

Capturing Subprocess Output in a String

To capture the output of a system call initiated through Python's subprocess.Popen and store it in a string, Python provides several options depending on the version you're using.

Python 2.7 or Python 3:

Leverage the subprocess.check_output() function:

from subprocess import check_output
output = check_output(["ntpq", "-p"])
Copy after login

Python 2.4-2.6:

Employ the Popen command's communicate method:

import subprocess
process = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
output, _ = process.communicate()
Copy after login

Note that when specifying the command, separate the executable and options into a list, such as ["ntpq", "-p"], as Popen does not invoke a shell.

The above is the detailed content of How Can I Capture Subprocess Output as a String 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