Skip to content

Instantly share code, notes, and snippets.

@moskytw
Last active November 6, 2017 09:52
Show Gist options
  • Save moskytw/09378b56483a970124bc828fa2420e60 to your computer and use it in GitHub Desktop.
Save moskytw/09378b56483a970124bc828fa2420e60 to your computer and use it in GitHub Desktop.
parent.py write to and read from the child.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
while True:
s = raw_input('Child: ')
if not s:
break
print 'Child:', s
print 'End of child.'
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
pty_master_fd, pty_slave_fd = os.openpty()
p = subprocess.Popen(
['python', 'child.py'],
stdin=subprocess.PIPE,
stdout=pty_slave_fd,
)
pty_master_f = os.fdopen(pty_master_fd)
while True:
s = raw_input('Parent: ')
p.stdin.write(s)
p.stdin.write('\n')
print '--- Output From Child ---'
print pty_master_f.readline()
print '--- End ---'
print
if not s:
break
print 'End of parent.'
$ py child.py
Child: 1
Child: 1
Child: 2
Child: 2
Child: 3
Child: 3
Child: ^CTraceback (most recent call last):
File "child.py", line 7, in <module>
s = raw_input('Child: ')
KeyboardInterrupt
$ py parent.py
Parent: 1
--- Output From Child ---
Child: Child: 1
--- End ---
Parent: 2
--- Output From Child ---
Child: Child: 2
--- End ---
Parent: 3
--- Output From Child ---
Child: Child: 3
--- End ---
Parent: ^CTraceback (most recent call last):
File "child.py", line 7, in <module>
s = raw_input('Child: ')
KeyboardInterrupt
Traceback (most recent call last):
File "parent.py", line 20, in <module>
s = raw_input('Parent: ')
KeyboardInterrupt
@dacapo1142
Copy link

dacapo1142 commented Nov 6, 2017

You need to add sys.stdout.flush() in the child.py, right after the print

@moskytw
Copy link
Author

moskytw commented Nov 6, 2017

Updated parent.py with the pty trick while child.py stays same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment