Skip to content

Instantly share code, notes, and snippets.

@harrisont
Last active March 23, 2022 00:32
Show Gist options
  • Save harrisont/b5b4bf311c2475a31fab5fa573cf3466 to your computer and use it in GitHub Desktop.
Save harrisont/b5b4bf311c2475a31fab5fa573cf3466 to your computer and use it in GitHub Desktop.
Python: live output from subprocess command
# 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)
@ReddyKilowatt
Copy link

The above does not work on Python 3
for line in iter(process .stdout.readline):
 TypeError: 'builtin_function_or_method' object is not iterable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment