python-asyncio - Python 异步输入
问题描述
我正在尝试在获取用户输入期间执行一些操作。我发现了这个问题,但两个答案都不适合我。
我的代码:
In [1]: import asyncio
In [2]: import aioconsole
In [3]:
In [3]:
In [3]: async def test():
...: await asyncio.sleep(5)
...: await aioconsole.ainput('Is this your line? ')
...: await asyncio.sleep(5)
In [4]: asyncio.run(test()) # sleeping, input, sleeping (synchronously)
我期望在睡眠期间可以访问输入(或例如简单的计数),但它没有发生。我做错了什么?
解决方案
我做错了什么?
您使用await
了 ,(顾名思义)表示“等待”。如果您希望事情同时发生,您需要告诉它们在后台运行,例如 usingasyncio.create_task()
或并发,例如 using asyncio.gather()
。例如:
async def say_hi(message):
await asyncio.sleep(1)
print(message)
async def test():
_, response, _ = await asyncio.gather(
say_hi("hello"),
aioconsole.ainput('Is this your line? '),
say_hi("world"),
)
print("response was", response)
asyncio.run(test())
推荐阅读
- tensorflow - Keras 未导入:TypeError:只能将 str(不是“列表”)连接到 str?
- ruby - Ruby 脚本的部署失败
- visual-studio - 如何在 Visual Studio 2019 中将项目模板与项目类型相关联?
- python-3.x - Pandas Df 的 Not In 逻辑表达式
- java - 使用 Java 流从嵌套地图中提取列表
- sql - 在 Oracle Query 中对 json 数组进行分组
- amazon-web-services - AWS DMS:从 RDS SQL Server 迁移到 Kinesis Streams 时出错
- c++ - 模板模板参数推导:三种不同的编译器三种不同的行为
- python - 列表理解从 JSON 中获取值
- scala - Spark ML 将自定义 OneHotEncoder 插入/拟合到管道中