Skip to content

Instantly share code, notes, and snippets.

@yunwilliamyu
Last active December 28, 2016 23:32
Show Gist options
  • Save yunwilliamyu/4301ddc0eecc22ade18607a18f3bda45 to your computer and use it in GitHub Desktop.
Save yunwilliamyu/4301ddc0eecc22ade18607a18f3bda45 to your computer and use it in GitHub Desktop.
Streaming stdin and stdout for subprocess progress reports
# If you don't need streaming stdout, just use communicate to access stdout and stderr instead
import threading
import subprocess
import sys
pr = subprocess.Popen(['command'], env=my_env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
def pipe_writer():
pr.stdin.write(input)
pr.stdin.close()
thread = threading.Thread(target=pipe_writer)
thread.start()
while pr.poll() is None:
l = pr.stdout.readline()
sys.stdout.write(l)
sys.stdout.flush()
thread.join() # This shouldn't be necessary, but just being safe.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment