首页 > 解决方案 > 与 Python 异步从管道子进程获取流

问题描述

我想直接运行以下命令Python

dumpcap -q -f http -i eth0 -w - | tshark -l -n -T json -r - | my_app.py

我想通过使用subprocess和运行它来asyncio运行它async

所以起初我想运行:

dumpcap -q -f http -i eth0 -w -

此输出应通过管道传输到下一个命令,该命令应该/可以不同步运行:

tshark -l -n -T json -r -

这个输出应该通过管道传输到我可以使用的流中。

有没有一个简单的解决方案?

标签: pythonpython-3.xsubprocesspython-asyncio

解决方案


除了@user4815162342的回答,请注意,您可以简单地将完整的shell命令传递给create_subprocess_shell并使用管道与子进程的两端进行通信:

例子:

proc = await asyncio.create_subprocess_shell(
    "tr a-z A-Z | head -c -2 | tail -c +3",
    stdin=asyncio.subprocess.PIPE,
    stdout=asyncio.subprocess.PIPE,
)
stdout, _ = await proc.communicate(b"**hello**")
assert stdout == b"HELLO"

推荐阅读