Created
January 20, 2018 17:56
-
-
Save phizaz/e81d3d362e89bc68055cfcd670d44e9b to your computer and use it in GitHub Desktop.
python subprocess's Popen live-output with "select"
This file contains 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 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