Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scythargon/34d39ca5f182c2d6194a to your computer and use it in GitHub Desktop.
Save scythargon/34d39ca5f182c2d6194a to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
# parent.py
import sys
from subprocess import Popen, PIPE
with Popen([sys.executable, "child.py"], stdout=PIPE, stdin=PIPE, bufsize=1,
universal_newlines=True) as p:
for line in sys.stdin:
line = line.rstrip('\n')
print(line, file=p.stdin, flush=True)
print(p.stdout.readline().rstrip('\n'), flush=True)
#!/usr/bin/python3
# child.py
import sys
for line in sys.stdin:
line = line.rstrip('\n')
print(line.upper(), flush=True)
#####
## multiple children example
#####
#!/usr/bin/python3
# parent.py
import sys
import time
from subprocess import Popen, PIPE
children = []
for i in range(5):
p = Popen([sys.executable, "child.py", "%s" % i], stdout=PIPE, stdin=PIPE, bufsize=1,
universal_newlines=True)
children.append(p)
while children:
for child in children:
while child.poll() is None:
line = child.stdout.readline().rstrip('\n')
if line == "over" or not line:
break
print(line, flush=True)
if child.poll() is not None:
children.remove(child)
time.sleep(0.1)
#!/usr/bin/python3
# child.py
import time
import sys
num = sys.argv[1]
for i in range(3):
print("Children %s: %s" % (num, i), flush=True)
print("over", flush=True)
time.sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment