Python - read output from long-running subprocess

2019-07-23 06:35发布

问题:

This question already has an answer here:

  • Read streaming input from subprocess.communicate() 6 answers

Using the subprocess module (Python 2.7), I'm running a command and attempting to process its output as it runs.

I have code like the following:

process = subprocess.Popen(
    ['udevadm', 'monitor', '--subsystem=usb', '--property'],
    stdout=subprocess.PIPE)
for line in iter(process.stdout.readline, ''):
    print(line)

However, the output only gets printed after I Ctrl+C, even if I add sys.stdout.flush() after the print statement.

Why is this happening, and how can I live stream the output from this process?

Notably, this udevadm monitor command is not intended to terminate, so I can't simply wait for the process to terminate and process its output all at once.

I found live output from subprocess command but the approach in the accepted answer did not solve my problem.

回答1:

You could use unbuffer :

process = subprocess.Popen(
    ["unbuffer", 'udevadm', 'monitor', '--subsystem=usb', '--property'],
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
    print(line)