我如何 运行 这个程序是异步的?

How do i run this program asynchronously?

作为 python AsyncIO 的新手,我写了一个示例厨师和服务员问题。

import asyncio

async def waiter():
    t1 = asyncio.create_task(cook('indian', 10))
    t2 = asyncio.create_task(cook('chinese', 5))
    t3 = asyncio.create_task(cook('american', 15))

    await t1
    await t2
    await t3


async def cook(name, time):
    print('Preparing {}'.format(name))
    await asyncio.sleep(time)
    print('Prepared {}'.format(name))

asyncio.run(waiter())

ubuntu@ip-172-31-14-144:~$ python3 one.py 
Preparing indian
Preparing chinese
Preparing american
Prepared chinese
Prepared indian
Prepared american
ubuntu@ip-172-31-14-144:~$ 

我从上面了解到one.py,服务员接了所有的单子,然后交给厨师处理。所以为了进一步加深理解,我想到了做一个菜单驱动的程序,让用户可以选择。

import asyncio
import aioconsole

menu = {
    'item1': 10,
    'item2': 5,
    'item3': 25,
    'item4': 5
}

queue = asyncio.Queue()
tasks = []

async def cook():

    print('In queue')
    user_option = await queue.get()
    user_option -= 1
    print(user_option)
    print('Preparing {}'.format(list(menu.keys())[user_option-1]))
    await asyncio.sleep(menu[list(menu.keys())[user_option-1]])
    print('Prepared {}'.format(list(menu.keys())[user_option-1]))


async def get_input():

    inp = await aioconsole.ainput('Please enter your desired option\n')
    return int(inp)


async def waiter():

    user_option = 0
    while True:
        count = 1
        print('*'*100)
        print('Hello User..\n')
        print('What would you like to have ??\n')
        for item in menu:
            print('{}. {}'.format(count, item))
            count = count + 1
        try:
            user_option = await asyncio.wait_for(get_input(), timeout=2.0)
        except asyncio.TimeoutError:
            print('TIMEOUT')

        if user_option:
            await queue.put(user_option)
            tasks.append(asyncio.create_task(coro=cook()))
            for i in tasks:
                await i
        else:
            print('In else')
            pass


asyncio.run(waiter())

****************************************************************************************************
Hello User..

What would you like to have ??

1. item1
2. item2
3. item3
4. item4
Please enter your desired option
TIMEOUT
In else
****************************************************************************************************
Hello User..

What would you like to have ??

1. item1
2. item2
3. item3
4. item4
Please enter your desired option
1 -> an option is entered here
In queue
0
Preparing item4 # Item is being prepared, but the intention is this should be happening
Prepared item4  # concurrently, so that other users can place their order
****************************************************************************************************
Hello User..

What would you like to have ??

1. item1
2. item2
3. item3
4. item4
Please enter your desired option

期望: 在第二个程序中,当输入一个选项时,厨师应该处理它们并将它们同时打印在屏幕上,而用户可以下订单,即使厨师正在准备一些东西。

问题: 一旦输入选项,服务员功能就会等待厨师完成,然后显示菜单。

Python 使用 3.8.10

谢谢

import asyncio
import aioconsole


menu = {
    'item1': 10,
    'item2': 5,
    'item3': 25,
    'item4': 5
}

tasks = []


#async def cook(queue):
#
#    print('In queue')
#    user_option = await queue.get()
#    user_option -= 1
#    print(user_option)
#    print('Preparing {}'.format(list(menu.keys())[user_option-1]))
#    await asyncio.sleep(menu[list(menu.keys())[user_option-1]])
#    print('Prepared {}'.format(list(menu.keys())[user_option-1]))
#
async def cook(queue):
    while True:
        print('In queue')
        user_option = await queue.get()
        user_option -= 1
        print(user_option)
        print('Preparing {}'.format(list(menu.keys())[user_option-1]))
        await asyncio.sleep(menu[list(menu.keys())[user_option-1]])
        print('Prepared {}'.format(list(menu.keys())[user_option-1]))

async def get_input():

    inp = await aioconsole.ainput('Please enter your desired option\n')
    return int(inp)


async def waiter(queue):

    user_option = 0
    while True:
        count = 1
        print('*'*100)
        print('Hello User..\n')
        print('What would you like to have ??\n')
        for item in menu:
            print('{}. {}'.format(count, item))
            count = count + 1
        try:
            user_option = await asyncio.wait_for(get_input(), timeout=1.0)
            print('You entered {}'.format(user_option))
        except asyncio.TimeoutError:
            pass

        if user_option > 0:
            print('Inserting option into queue {}'.format(user_option))
            await queue.put(user_option)
            user_option = -1
        await asyncio.sleep(3)

async def main():

    queue = asyncio.Queue()
    task1 = asyncio.create_task(waiter(queue))
    task2 = asyncio.create_task(cook(queue))

    await asyncio.gather(task1, task2)

asyncio.run(main())

服务员现在可以同时接受订单,并且烹饪函数会在准备好食物时打印出来。