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

How Can I Efficiently Store Subprocess Output as a String in Python?

Linda Hamilton
Release: 2024-12-06 15:21:15
Original
850 people have browsed it

How Can I Efficiently Store Subprocess Output as a String in Python?

Storing Subprocess Output in a String

When executing system calls in Python, storing the results in a string for further manipulation becomes crucial. This article explores how to achieve this effectively using subprocess.Popen in Python.

Consider the example below:

import subprocess

# Create a Popen object to execute the ntpq command
p2 = subprocess.Popen("ntpq -p")
Copy after login

To store the output of this command in a string, there are two primary approaches:

Method 1: subprocess.check_output (Python 2.7 or Python 3)

This function combines Popen with communication handling to return the stdout output as a string.

from subprocess import check_output

# Execute the command and store the output in a string
out = check_output(["ntpq", "-p"])
Copy after login

Method 2: communicate (Python 2.4-2.6)

For older Python versions, the communicate method is utilized.

import subprocess

# Create a Popen object with stdout connected to a pipe
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)

# Read the stdout output and store it in a string
out, err = p.communicate()
Copy after login

Note that the command should be provided as a list, as Popen doesn't invoke the shell.

The above is the detailed content of How Can I Efficiently Store Subprocess Output as a String in Python?. For more information, please follow other related articles on the PHP Chinese website!

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