Last active
December 28, 2016 23:32
-
-
Save yunwilliamyu/4301ddc0eecc22ade18607a18f3bda45 to your computer and use it in GitHub Desktop.
Streaming stdin and stdout for subprocess progress reports
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
# 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