首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >input的问题(Python中的异步输入)

input的问题(Python中的异步输入)
EN

Stack Overflow用户
提问于 2022-05-23 16:32:34
回答 1查看 93关注 0票数 1

我有一个队列变量和一个输入顺序。如果队列有什么内容,我必须强制输入命令停止。我不得不使用异步模块来完成这个任务。举个例子,让我们看看下面的代码:

代码语言:javascript
运行
复制
import asyncio
import multiprocessing
import time
from aioconsole import ainput


def my_function(queue):
    time.sleep(3)
    queue.put(5)


async def my_loop(queue):
    while True:
        await asyncio.sleep(0.1)
        if not queue.empty():
            break


async def main():
    queue = multiprocessing.Queue()
    p = multiprocessing.Process(target=my_function, args=(queue,))
    p.start()
    task1 = asyncio.create_task(ainput("Enter text:"))
    task2 = asyncio.create_task(my_loop(queue))
    await asyncio.wait([task1, task2], return_when='FIRST_COMPLETED')
    try:
        text = task1.result()
        q = ""
    except asyncio.exceptions.InvalidStateError:
        text = ""
        q = queue.get()
    print('Doing stuff with input %s/%s...' % (text, q))

当队列上有什么内容或用户输入一些文本时,程序就会结束。我的真正的程序连续有几个这样的输入命令,如下所示:

代码语言:javascript
运行
复制
import asyncio
import multiprocessing
import time
from aioconsole import ainput


def my_function(queue):
    time.sleep(3)
    queue.put(5)


async def my_loop(queue):
    while True:
        await asyncio.sleep(0.1)
        if not queue.empty():
            break


async def main():
    queue = multiprocessing.Queue()
    p = multiprocessing.Process(target=my_function, args=(queue,))
    p.start()
    task1 = asyncio.create_task(ainput("Enter text:"))
    task2 = asyncio.create_task(my_loop(queue))
    await asyncio.wait([task1, task2], return_when='FIRST_COMPLETED')
    try:
        text = task1.result()
        q = ""
    except asyncio.exceptions.InvalidStateError:
        text = ""
        q = queue.get()
    print('Doing stuff with input %s/%s...' % (text, q))


    task1 = asyncio.create_task(ainput("Next: "))
    task2 = asyncio.create_task(my_loop(queue))
    await asyncio.wait([task1, task2], return_when='FIRST_COMPLETED')

    try:
        text = task1.result()
        q = ""
    except asyncio.exceptions.InvalidStateError:
        text = ""
        q = queue.get()
    print('Doing stuff with input %s/%s...' % (text, q))


    

if __name__ == '__main__':
    asyncio.run(main())

问题是,如果我第一次等待队列,第二次,我必须输入两次输入,就像第一次输入仍然在等待什么。如果用户什么都不写,你知道我怎么才能“打破”第一个输入?提前感谢

EN

回答 1

Stack Overflow用户

发布于 2022-05-24 01:11:38

如果我正确理解了您的意思,您可以在取消所有挂起的任务的步骤之间使用task.cancel()

代码语言:javascript
运行
复制
import asyncio
import multiprocessing
import time
from aioconsole import ainput


def my_function(queue):
    time.sleep(3)
    queue.put(5)


async def my_loop(queue):
    while True:
        await asyncio.sleep(0.1)
        if not queue.empty():
            break


async def main():
    queue = multiprocessing.Queue()
    p = multiprocessing.Process(target=my_function, args=(queue,))
    p.start()

    task1 = asyncio.create_task(ainput("Enter text:"))
    task2 = asyncio.create_task(my_loop(queue))
    tasks = [task1, task2]

    await asyncio.wait(tasks, return_when="FIRST_COMPLETED")
    try:
        text = task1.result()
        q = ""
    except asyncio.exceptions.InvalidStateError:
        text = ""
        q = queue.get()

    print()
    print("1. Doing stuff with input %s/%s..." % (text, q))

    # cancel all tasks:
    for t in [task1, task2]:
        t.cancel()

    # Wait until all worker tasks are cancelled:
    await asyncio.gather(*tasks, return_exceptions=True)

    task1 = asyncio.create_task(ainput("Next: "))
    task2 = asyncio.create_task(my_loop(queue))
    tasks = [task1, task2]

    await asyncio.wait(tasks, return_when="FIRST_COMPLETED")

    try:
        text = task1.result()
        q = ""
    except asyncio.exceptions.InvalidStateError:
        text = ""
        q = queue.get()

    print()
    print("2. Doing stuff with input %s/%s..." % (text, q))


if __name__ == "__main__":
    asyncio.run(main())

打印(例如):

代码语言:javascript
运行
复制
Enter text:
1. Doing stuff with input /5...
Next: Hello World

2. Doing stuff with input Hello World/...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72351945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档