为 Python Asyncio 立即返回 stdout 和 stderr

问题描述 投票:0回答:0

我有安排两个任务(都是简单的 python 脚本)并运行它们的代码。但是,我想阅读通过任务编写的标准输出/标准错误。目前,我的代码只在子进程完成后才返回它们

下面是两个简单的脚本,它们只打印到标准输出以及运行异步子进程的

main.py

hello_europe.py

import time

print("Hello Europe!!")
print("I am going to sleep for 5 seconds...")
time.sleep(5)
print("done sleeping! waking up now! :)")

你好_美国.py

print("Hello USA!!")

main.py

import asyncio
import sys

if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())

async def _watch(stream, prefix="") -> None:
    async for line in stream:
        print(prefix, line.decode().rstrip())

async def _run_cmd(cmd) -> None:
    # Create subprocess
    proc = await asyncio.create_subprocess_shell(
        cmd, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )

    # I assume this is where something is going wrong
    await _watch(proc.stdout, "stdout:")
    await _watch(proc.stderr, "stderr:")

    # This will wait until subprocess finishes! We do not want that!
    # stdout, stderr = await proc.communicate()
    # if stdout:
    #     print(f"stdout:\n{stdout.decode()}")
    # if stderr:
    #     print(f"stderr\n{stderr.decode()}")

def get_tasks() -> list[str]:
    europe_tasks: list[str] = [
        "python hello_europe.py"
    ]

    usa_tasks: list[str] = [
        "python hello_usa.py"
    ]
    return usa_tasks + europe_tasks

async def _run_all() -> None:
    tasks: list[str] = get_tasks()

    hello_tasks: list[asyncio.Task] = [
        asyncio.create_task(_run_cmd(i))
        for i in tasks
    ]
    await asyncio.wait(hello_tasks)

def main() -> None:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(_run_all())
    loop.close()

if __name__ == "__main__":
    main()

python async-await python-asyncio
© www.soinside.com 2019 - 2024. All rights reserved.