python - How to stream stdout/stderr from a child process using asyncio, and obtain its exit code after? -
under python 3.4 on windows, need stream info written stdout/stderr kid process, i.e. receive output occurs, using asyncio framework introduced in python 3.4. have determine program's exit code afterwards. how can this?
the solution i've come far uses subprocessprotocol receive output kid process, , associated transport process' exit code. don't know if optimal though. i've based approach on answer similar question j.f. sebastian.
import asyncio import contextlib import os import locale class subprocessprotocol(asyncio.subprocessprotocol): def pipe_data_received(self, fd, data): if fd == 1: name = 'stdout' elif fd == 2: name = 'stderr' text = data.decode(locale.getpreferredencoding(false)) print('received {}: {}'.format(name, text.strip())) def process_exited(self): loop.stop() if os.name == 'nt': # on windows, proactoreventloop necessary hear on pipes loop = asyncio.proactoreventloop() asyncio.set_event_loop(loop) else: loop = asyncio.get_event_loop() contextlib.closing(loop): # connect process transport = loop.run_until_complete(loop.subprocess_exec( subprocessprotocol, 'python', '-c', 'print(\'hello async world!\')'))[0] # wait until process has finished loop.run_forever() print('program exited with: {}'.format(transport.get_returncode())) python asynchronous python-3.4 python-asyncio
No comments:
Post a Comment