Created
June 15, 2014 21:12
-
-
Save movEAX/b8c9e6b83acc44dc5c80 to your computer and use it in GitHub Desktop.
Asyncio interactive subprocess communication, where subprocess is python script.
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
''' | |
test.py look like this:: | |
msg = 'prompt' | |
for i in range(1, 4): | |
msg = input(msg * i + '\n') | |
''' | |
import sys | |
import asyncio | |
@asyncio.coroutine | |
def interactive_popen(): | |
proc = yield from asyncio.create_subprocess_exec( | |
sys.executable, '-u', 'test.py', # python --help | grep '\-u' | |
stdin=asyncio.subprocess.PIPE, | |
stdout=asyncio.subprocess.PIPE) | |
try: | |
while True: | |
print((yield from proc.stdout.readline()).decode()) | |
# note what sign of new line is required | |
proc.stdin.write(b'test\n') | |
drain = proc.stdin.drain() | |
if drain is not (): | |
yield from drain | |
except ConnectionResetError: | |
pass | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(interactive_popen()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment