Skip to content

Instantly share code, notes, and snippets.

@zed
Created March 13, 2013 07:34
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/3b4606d811fcf6530795 to your computer and use it in GitHub Desktop.
Save zed/3b4606d811fcf6530795 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""Read 10M lines from a subprocess stdout.
Write to the subprocess' stdin periodically.
"""
import sys
from subprocess import Popen, PIPE
from textwrap import dedent
def main():
p = Popen([sys.executable, "-c", dedent("""
import itertools, sys
for i in itertools.count():
print(i)
if i % 1000000 == 0: # read input every 1M lines
sys.stdout.flush() # make sure the prompt (1M line) is sent
print(sys.stdin.readline().strip()[::-1]) # reverse line
""")], stdin=PIPE, stdout=PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
i = int(line)
if i % 1000000 == 0: # write to the subprocess every 1M lines
p.stdin.write(b'abc\n')
p.stdin.flush()
response = p.stdout.readline()
if response.strip() != b'cba': # should receive reversed line
sys.stderr.write('error %d %r' % (i, response,))
sys.stderr.write('.')
sys.stderr.flush()
if i == 10*1000000: # 10M lines
break
p.stdin.close()
p.stdout.close()
p.terminate()
p.wait()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment