Home >Backend Development >Python Tutorial >How Can I Capture and Store the Output of a subprocess.Popen Call as a String in Python?

How Can I Capture and Store the Output of a subprocess.Popen Call as a String in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-04 19:07:14341browse

How Can I Capture and Store the Output of a subprocess.Popen Call as a String in Python?

Storing Output of subprocess.Popen Call in a String

In Python programming, using the subprocess module allows you to execute system calls and capture their output. This article provides solutions for storing the output of a subprocess.Popen call in a string variable.

Solution for Python 2.7 or Python 3

Python provides the subprocess.check_output() function, specifically designed for capturing the output of a command into a string. Simply use it as follows:

from subprocess import check_output
out = check_output(["ntpq", "-p"])

Solution for Python 2.4-2.6

For Python versions 2.4 to 2.6, you can utilize the communicate method of Popen:

import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()

The out variable in the above code contains the desired output.

Note Regarding Command Input

When utilizing Popen, it's crucial to pass the command as a list of strings, as shown in the examples provided. This is because Popen does not invoke the shell.

The above is the detailed content of How Can I Capture and Store the Output of a subprocess.Popen Call 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