python 管道 异步读取 stdout select_Python异步子进程连续写入stdin和读取stdout/stderr...

本文探讨了在Python3的asyncio库中,如何处理子进程的异步读写操作,特别是涉及stdin、stdout和stderr时可能遇到的死锁问题。通过示例代码展示了读写过程,并引用了警告,指出使用`communicate()`方法可以避免死锁。文章最后询问了如何在确保没有死锁的情况下,连续写入stdin并同时读取stdout和stderr的方法。
摘要由CSDN通过智能技术生成

我目前正在执行一项任务,其中包含python3asyncio中的子进程。我的代码只需同时写入stdin和读取stdout/stderr:import asyncio

async def read_stdout(stdout):

print('read_stdout')

while True:

buf = await stdout.read(10)

if not buf:

break

print(f'stdout: { buf }')

async def read_stderr(stderr):

print('read_stderr')

while True:

buf = await stderr.read()

if not buf:

break

print(f'stderr: { buf }')

async def write_stdin(stdin):

print('write_stdin')

for i in range(100):

buf = f'line: { i }\n'.encode()

print(f'stdin: { buf }')

stdin.write(buf)

await stdin.drain()

await asyncio.sleep(0.5)

async def run():

proc = await asyncio.create_subprocess_exec(

'/usr/bin/tee',

stdin=asyncio.subprocess.PIPE,

stdout=asyncio.subprocess.PIPE,

stderr=asyncio.subprocess.PIPE)

await asyncio.gather(

read_stderr(proc.stderr),

read_stdout(proc.stdout),

write_stdin(proc.stdin))

asyncio.run(run())Warning Use the communicate() method rather than process.stdin.write(), await process.stdout.read() or await process.stderr.read. This avoids deadlocks due to streams pausing reading or writing and blocking the child process.

这是否意味着上述代码在某些情况下会陷入死锁?如果是这样的话,如何在python3异步中连续地写stdin和读stdout/stderr,而没有死锁?在

非常感谢。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值