Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

python subprocess 的Popen怎么创建异步进程

  1. User

    python subprocess 的Popen怎么创建异步进程

  2. Assistant

    使用 Popen 的子类 asyncio.subprocess.Popen 来创建异步进程。该子类是 async/await 可用的,这意味着您可以等待异步进程完成而无需使用回调。以下是一个示例代码:

    import asyncio from asyncio.subprocess import PIPE

    async def run_command(): # 创建异步进程 process = await asyncio.create_subprocess_exec( 'ls', '-lh', stdout=PIPE, stderr=PIPE )

    # 等待进程完成,并读取输出结果
    stdout, stderr = await process.communicate()
    
    # 输出结果
    print(f'stdout: {stdout.decode()}')
    print(f'stderr: {stderr.decode()}')
    

    运行异步进程

    asyncio.run(run_command())

    在上面的代码中,使用 create_subprocess_exec() 来创建异步进程。请注意,将 stdout 和 stderr 传递到 PIPE,以便可以读取子进程输出。然后,通过调用 communicate() 方法等待进程完成并读取输出结果。最后,输出结果并使用 asyncio.run() 运行异步进程。