Last active
March 23, 2022 00:32
-
-
Save harrisont/b5b4bf311c2475a31fab5fa573cf3466 to your computer and use it in GitHub Desktop.
Python: live output from subprocess command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From http://stackoverflow.com/a/18422264 | |
import subprocess | |
import sys | |
with open('test.log', 'w') as f: | |
process = subprocess.Popen(your_command, stdout=subprocess.PIPE) | |
for line in iter(process.stdout.readline, ''): # With Python 3, you need iter(process.stdout.readline, b'') (i.e. the sentinel passed to iter needs to be a binary string, since b'' != '') | |
sys.stdout.write(line) | |
f.write(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above does not work on Python 3
for line in iter(process .stdout.readline):
TypeError: 'builtin_function_or_method' object is not iterable