Skip to content

Instantly share code, notes, and snippets.

@zed
Last active June 10, 2017 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/753c033010ca5f68577572a147247313 to your computer and use it in GitHub Desktop.
Save zed/753c033010ca5f68577572a147247313 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""Print a random number of lines in response to each input line.
Terminate each response with 'END'.
"""
import sys
import random
def log(msg):
return print(msg, file=sys.stderr)
for line in sys.stdin:
log('input: %r' % line)
response = line * random.randint(1, 5) + 'END'
log('response: %r' % response)
# NOTE: flush stdout buffer to make the response available to the parent
print(response, flush=True)
#!/usr/bin/env python3
"""Run interactive subprocess.
Input depends on the previous output from the child process.
The child process has to flush its stdout buffer at the end of each
response. Otherwise the code blocks. Threads, non-blocking IO won't
help here: the next input can't be sent until the previous response is
flushed by the child. The buffering in the child has to change
https://stackoverflow.com/questions/20503671/python-c-program-subprocess-hangs-at-for-line-in-iter
"""
import sys
from subprocess import Popen, PIPE
with Popen([sys.executable, 'child.py'], stdin=PIPE, stdout=PIPE,
bufsize=1, universal_newlines=True) as p:
s = 'a'
while len(s) < 10: # an arbitrary condition to stop
print(s, file=p.stdin) # send input
s = ''.join(iter(p.stdout.readline, 'END\n')) # get output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment