Skip to content

Instantly share code, notes, and snippets.

@phizaz
Created January 20, 2018 17:56
Show Gist options
  • Save phizaz/e81d3d362e89bc68055cfcd670d44e9b to your computer and use it in GitHub Desktop.
Save phizaz/e81d3d362e89bc68055cfcd670d44e9b to your computer and use it in GitHub Desktop.
python subprocess's Popen live-output with "select"
from select import select
import os
import time
import subprocess
from contextlib import contextmanager
@contextmanager
def pipe():
r, w = os.pipe()
yield r, w
os.close(r)
os.close(w)
with pipe() as (r, w):
cmd = 'echo test'
with subprocess.Popen(cmd, shell=True, stdout=w, stderr=w) as p:
while p.poll() is None:
# get read buffer from the output when ready without blocking
while len(select([r], [], [], 0)[0]) > 0:
# read 1024 bytes from the buffer
buf = os.read(r, 1024)
print(buf.decode('utf-8'), end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment