Asyncio流子进程输出和pdb

时间:2019-12-10 03:00:01

标签: python subprocess python-asyncio

在我的特定用例中,我正在编写一个脚本来启动多个开发服务器。

子流程的输出流式传输到stdout。但是,如果我在其中一个开发服务器中输入了breakpoint(),则不会显示pdb输入提示。尽管pdbstdin很好,但它不响应arrow-up arrow-down来浏览bash历史记录。

是否可以通过asyncio解决这个问题,还是必须诉诸threading

这是我脚本的相关部分:

async def run_dev_servers():
    await asyncio.gather(
        start_stream_subprocess('flask run --port 5000', APP_PATH_1, ENV_1),
        start_stream_subprocess('flask run --port 8000', APP_PATH_2, ENV_2),
    )


async def start_stream_subprocess(cmd, cwd=CWD, env=None):
    proc = await asyncio.create_subprocess_shell(
        cmd,
        cwd=cwd,
        env=env,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    try:
        await asyncio.wait([print_stream(proc.stdout), print_stream(proc.stderr)])
    except Exception:
        # Terminate process on all exceptions
        proc.terminate()


async def print_stream(stream):
    while True:
        line = await stream.readline()
        if line:
            print(line.decode('utf-8'), end='')
        else:
            break


if __name__ == '__main__':
    try:
        asyncio.run(run_dev_servers())
    except KeyboardInterrupt:
        print('\n Killed servers')

0 个答案:

没有答案