子进程

源代码: Lib/asyncio/subprocess.py , Lib/asyncio/base_subprocess.py


此节描述的高级 async/await asyncio API 能创建和管理子进程。

这里是 asyncio 如何运行 Shell 命令并获得其结果的范例:

import asyncio
async def run(cmd):
    proc = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)
    stdout, stderr = await proc.communicate()
    print(f'[{cmd!r} exited with {proc.returncode}]')
    if stdout:
        print(f'[stdout]\n{stdout.decode()}')
    if stderr:
        print(f'[stderr]\n{stderr.decode()}')
asyncio.run(run('ls /zzz'))