以与Python异步的方式从管道子流程获取流

2024-04-25 01:59:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想直接在Python中运行以下命令:

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

我想通过使用subprocessasyncio来运行它,让它在async中运行

因此,首先我想运行:

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

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

tshark -l -n -T json -r -

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

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


Tags: py命令asynciojsonapphttpasync管道
2条回答

除了@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"

Is there a straightforward solution for this?

子流程文档中的example也应适用于异步IO子流程。例如(未经测试):

async def process():
    p1 = await asyncio.create_subprocess_shell(
        "dumpcap -q -f http -i eth0 -w -", stdout=asyncio.subprocess.PIPE)
    p2 = await asyncio.create_subprocess_shell(
        "tshark -l -n -T json -r -",
        stdin=p1.stdout, stdout=asyncio.subprocess.PIPE)
    p1.stdout.close()  # we no longer need it

    while True:
        line = await p2.stdout.readline()
        if not line:
            break
        print(line)

相关问题 更多 >