How to stream stdout/stderr from a child process using asyncio, and obtain its exit code after?

前端 未结 3 1472
一向
一向 2020-12-19 15:51

Under Python 3.4 on Windows, I need to stream data written to stdout/stderr by a child process, i.e. receive its output as it occurs, using the asyncio framework introduced

3条回答
  •  别那么骄傲
    2020-12-19 16:41

    I guess to use high-level api:

    proc = yield from asyncio.create_subprocess_exec(
        'python', '-c', 'print(\'Hello async world!\')')
    
    stdout, stderr = yield from proc.communicate()
    
    retcode = proc.returncode
    

    Also you can do more:

    yield from proc.stdin.write(b'data')
    yield from proc.stdin.drain()
    
    stdout = yield from proc.stdout.read()
    stderr = yield from proc.stderr.read()
    
    retcode = yield from proc.wait()
    

    and so on.

    But, please, keep in mind that waiting for, say, stdout when child process prints nothing can hang you coroutine.

提交回复
热议问题