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
Susan SarandonOriginal
2024-12-02 21:27:121055browse

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"])

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

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!

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