python-3.x - 如何停止等待来自另一个协程/任务的输入函数
问题描述
我想在循环ainput
的第 6 次迭代中停止等待函数for
import asyncio
from aioconsole import ainput
class Test():
def __init__(self):
self.read = True
async def read_from_concole(self):
while self.read:
command = await ainput('$>')
if command == 'exit':
self.read = False
if command == 'greet':
print('greetings :J')
async def count(self):
console_task = asyncio.create_task(self.read_from_concole())
for c in range(10):
await asyncio.sleep(.5)
print(f'number: {c}')
if c == 5: # 6th iteration
# What shoud I do here?
# Following code doesn't meet my expectations
self.read = False
console_task.cancel()
await console_task
# async def run_both(self):
# await asyncio.gather(
# self.read_from_concole(),
# self.count()
# )
if __name__ == '__main__':
o1 = Test()
loop = asyncio.new_event_loop()
loop.run_until_complete(o1.count())
当然,这段代码被简化了,但涵盖了这个想法:编写一个程序,其中一个协程可以取消另一个正在等待的东西(在这个例子中ainput
.
asyncio.Task.cancel()
不是解决方案,因为它不会让协程停止等待(所以我需要放任意字符进入控制台并按回车,这不是我想要的)。
我什至不知道我的方法是否有意义,我是一个新的 asyncio 用户,现在,我只知道基础知识。在我的实际项目中,情况非常相似。我有一个 GUI 应用程序和一个控制台窗口。通过单击“X”按钮,我想关闭窗口并终止ainput
(从控制台读取命令)以完全完成程序(控制台部分正在另一个线程上工作,因此我无法完全关闭我的程序 -该线程将一直运行,直到ainput
收到用户的一些输入)。
解决方案
推荐阅读
- android - KeyStoreException:尝试解密时签名/MAC 验证失败
- android - NavigationComponent recyclerview 返回共享元素过渡
- java - 如何从数组中随机选择四个元素而不在 Java 中重复?
- javascript - NestJS WebSocketGateway 未初始化
- c - 无论如何,我可以在哪里比较使用指针制作的 struct 结构?
- tibco - [row,col {unknown-source}] 的属性值中出现意外的 EOF:[2,3861] TIBCO BW 6.3 中的 Web 服务回复问题
- scala - 发布本地正在将 Scala 版本添加到库的名称
- c# - 无法使用asp .net核心中的abp框架连接到sql数据库
- android - 字符串翻译(本地化)如何适用于特定语言和区域设置?
- button - 如何处理 DDDW 的 buttonclicked 事件?