【问题标题】:asyncio print something while waiting for user inputasyncio 在等待用户输入时打印一些东西
【发布时间】:2020-12-24 22:17:22
【问题描述】:

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

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,我该如何实现?

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    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 lib,它提供了基于异步的控制台功能:

    from aioconsole import ainput
    
    async def user_input():
        while True:
            content = await ainput(">")
            print(content)
    

    【讨论】:

    • 天哪,谢谢,其他答案都建议使用 10-30 行 java-esque factory factory 包装 stdin 和 stdout,而不仅仅是使用已经存在的“输入”功能。这应该是所有其他问题的答案。
    【解决方案2】:

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

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

    如果您想使用异步线程,请查看ThreadExecutor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多