Home > Backend Development > Python Tutorial > How can I Retrieve Realtime Output from a Command-line Program Using `subprocess` in Python?

How can I Retrieve Realtime Output from a Command-line Program Using `subprocess` in Python?

Barbara Streisand
Release: 2024-11-14 21:17:02
Original
969 people have browsed it

How can I Retrieve Realtime Output from a Command-line Program Using `subprocess` in Python?

Retrieving Realtime Output with Subprocess

To obtain real-time output from a command-line program using subprocess, the p.stdout.readline() method can be employed. This method differs from p.stdout in terms of buffering behavior. While p.stdout buffers output aggressively, p.stdout.readline() reads each line as it becomes available.

The following Python code demonstrates the use of p.stdout.readline():

from subprocess import Popen, PIPE, STDOUT

p = Popen('svnadmin verify /var/svn/repos/config', stdout=PIPE, stderr=STDOUT, shell=True)
while True:
    line = p.stdout.readline()
    if not line:
        break
    print(line.replace('\n', ''))
Copy after login

This code reads each line of output from the svnadmin verify command and prints it in real time.

The above is the detailed content of How can I Retrieve Realtime Output from a Command-line Program Using `subprocess` 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