Last active
November 6, 2017 09:52
-
-
Save moskytw/09378b56483a970124bc828fa2420e60 to your computer and use it in GitHub Desktop.
parent.py write to and read from the child.py
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
while True: | |
s = raw_input('Child: ') | |
if not s: | |
break | |
print 'Child:', s | |
print 'End of child.' |
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
#!/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 ---' | |
if not s: | |
break | |
print 'End of parent.' |
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
$ 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 |
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
$ 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated parent.py with the pty trick while child.py stays same.