Home >Backend Development >Python Tutorial >How to Display Real-time Program Output with Python's `subprocess`?

How to Display Real-time Program Output with Python's `subprocess`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 09:55:02942browse

How to Display Real-time Program Output with Python's `subprocess`?

Accessing Real-Time Program Output with Subprocess

Question:

How can we obtain real-time program output using subprocess in Python? Specifically, how can we display the progress of a command-line program without buffering the output?

Answer:

To get real-time output from a program executed with subprocess, we can use the following technique:

import subprocess

p = subprocess.Popen('svnadmin verify /var/svn/repos/config',
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True,
                     bufsize=0)  # Set bufsize to 0 for no buffering

while True:
    line = p.stdout.readline()
    if not line:
        break
    print(line.replace('\n', ''))

Explanation:

  • We set bufsize to 0 in Popen to disable output buffering.
  • In the while loop, we continuously read lines from p.stdout using readline().
  • If no line is available, the loop breaks and the program exits.
  • We can process or display each line as they are received, providing real-time output.

Note:

  • This method may not work on all systems or with all programs.
  • For Python 3.8 and above, consider using asyncio instead of raw file descriptors for handling subprocess output.

The above is the detailed content of How to Display Real-time Program Output with Python's `subprocess`?. 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