首页 > 解决方案 > 如何停止等待来自另一个协程/任务的输入函数

问题描述

我想在循环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收到用户的一些输入)。

标签: python-3.xpython-asyncio

解决方案


推荐阅读