You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python异步子进程不使用communicate传输入致进程无法终止求助

解决asyncio子进程无法终止的问题

你的代码存在两个核心问题,导致程序永久挂起:

  • 向子进程写入代码后未关闭stdin,子进程的Python解释器会一直等待更多输入,不会主动结束执行。
  • process.stdin.write()是异步操作,直接调用后数据可能滞留在缓冲区,未立即发送给子进程,导致子进程无法接收完整输入并执行。

修复方案1:手动处理流的写入与关闭

通过等待写入完成、排空缓冲区、关闭输入流的步骤,让子进程明确知道没有更多输入,从而正常退出:

import asyncio

async def main():
    process = await asyncio.create_subprocess_exec(
        'python3',
        stdin=asyncio.subprocess.PIPE
    )
    
    print('hi1')
    
    # 写入代码并等待异步操作完成
    await process.stdin.write("""import time 
print('whatsup') 
fo = open('foo.txt', 'w') 
fo.write('Python is a great language.') 
fo.close() 
time.sleep(3) 
print('yo')""".encode("utf-8"))
    
    # 确保缓冲区数据全部发送到子进程
    await process.stdin.drain()
    # 关闭输入流,告知子进程没有更多输入
    process.stdin.close()
    await process.stdin.wait_closed()
    
    print('end')
    
    await process.wait()

asyncio.run(main())

修复方案2:使用communicate()简化操作

asyncio.subprocess.Process的communicate()方法会自动处理输入发送、流关闭和进程等待,代码更简洁可靠:

import asyncio

async def main():
    process = await asyncio.create_subprocess_exec(
        'python3',
        stdin=asyncio.subprocess.PIPE
    )
    
    print('hi1')
    
    code = """import time 
print('whatsup') 
fo = open('foo.txt', 'w') 
fo.write('Python is a great language.') 
fo.close() 
time.sleep(3) 
print('yo')"""
    
    # 自动发送输入、关闭流并等待进程结束
    await process.communicate(input=code.encode("utf-8"))
    
    print('end')

asyncio.run(main())

内容的提问来源于stack exchange,提问作者devashish yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 06:21:36