1

我有一个简单的脚本,我希望用户能够随时输入一些东西,但我也想在中间打印一些东西,这是我的代码:

import asyncio

async def user_input():
   while True:
        content = input('> ')


async def print_something():
    await asyncio.sleep(10)
    print('something')


async def main():
    tasks = [user_input(), print_something()]
    await asyncio.gather(*tasks)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

它让我输入,但它不打印something,我该如何实现?

4

2 回答 2

2

input是一个阻塞函数,不能直接与内部协程一起使用。但是您可以通过以下方式在单独的线程中启动它run_in_executor

import asyncio


async def user_input():
    while True:
        loop = asyncio.get_event_loop()
        content = await loop.run_in_executor(None, input, "> ")
        print(content)


async def print_something():
    await asyncio.sleep(5)
    print('something')


async def main():
    tasks = [user_input(), print_something()]
    await asyncio.gather(*tasks)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

更新:您还可以使用aioconsole库,它提供基于异步的控制台功能:

from aioconsole import ainput

async def user_input():
    while True:
        content = await ainput(">")
        print(content)
于 2020-12-24T14:06:16.877 回答
0

简短的回答是 async 不能做你想要的。虽然您确实将函数声明为异步,但 python 函数input不是异步的,它是一个阻塞函数。所以它会阻塞事件循环并且不会运行其他任何东西。

不久前我回答了一个问题,有点解释了异步在 python 中的工作原理。我会链接它。但是为了做你想做的事,你需要使用线程而不是异步的。 https://stackoverflow.com/a/63237798/9270488

如果您想将线程与异步一起使用,请查看ThreadExecutor

于 2020-12-24T14:05:03.877 回答