You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Asyncio异步任务执行顺序异常 未按预期返回welcome函数

问题描述

我正在学习使用async异步函数,练习编写模拟AI对话的程序时,执行流程不符合预期:程序询问完用户姓名后,没有回到welcome函数执行「很高兴认识你」的输出逻辑,反而直接继续执行create_user()函数,等create_user()执行完成后,才返回welcome函数执行「是否创建用户」的询问步骤。

实际运行输出
>> Hello
>> Who are you?
>> What's your name? Moises
>> Tell me a user name you like: RD
>> Now tell me a password: 1234
>> User created!
>> Nice to meet you Moises!
>> would you like to create a user? y/n y
>> Nice, you have a username {user} and a password {}
>> now you are part of us!
问题代码
# practice.py
"""Simulating an IA using the asyncio function"""
import asyncio, time, os


def wait(): # To pause the conversation
    time.sleep(2)
    
async def welcome(): # the main function
    task = asyncio.create_task(data())
    task2 = asyncio.create_task(create_user())

    os.system('cls')

    print(">> Hello")
    wait()
    print(">> Who are you?")
    wait()
    return_value = await task # wait for task (data) to return the value with the name
    print(f">> Nice to meet you {return_value}!")
    wait()

    ask = input(">> would you like to create a user? y/n ") # Asking to create a user yes or no
    if ask == 'y':
        user, password  =  await task2 # waiting for task2 (create_user) to return values
        print(">> Nice, you have a username {user} and a password {}")
        wait()
        print(">> now you are part of us!")
    else:
        print(">> You can not interact with me if you don't have a user")
        wait()
        print(">> See you!")
        quit()

async def data(): # User personal data
    global name
    name = input(">> What's your name? ")
    return name
    

async def  create_user(): # User account data
    user = input(">> Tell me a user name you like: ")
    passw =input(">> Now tell me a password: ")
    wait()
    print(">> User created!")
    return user, passw
    
# Run the program
asyncio.run(welcome())
问题根因
  • asyncio.create_task()会将任务立刻提交到事件循环调度,你在welcome函数开头就同时提交了data()和create_user()两个任务,两个任务会在事件循环运行时并发执行,不会等调用await的时候才启动。
  • 代码中使用的time.sleep()是同步阻塞方法,执行时会卡住整个异步事件循环,无法实现非阻塞等待。
  • create_user任务在用户确认是否创建账号前就已经被调度执行,因此会在获取完姓名后直接弹出用户名、密码输入提示,打乱预期流程。
  • 打印账号信息的字符串没有加f前缀,变量无法被正确插值,最终输出的是原始占位符文本而非实际输入值。
修复方案
  • 不要提前创建create_user对应的任务,等用户输入y确认要创建账号时,再调用await执行create_user逻辑。
  • 把阻塞的time.sleep()替换为异步的asyncio.sleep(),避免卡住事件循环。
  • 给打印账号信息的字符串加上f前缀,正确插入用户名、密码变量。

修复后的完整代码:

# practice.py
"""使用asyncio模拟AI对话"""
import asyncio, os


async def wait(): # 异步暂停对话,不阻塞事件循环
    await asyncio.sleep(2)
    
async def welcome(): # 主函数
    os.system('cls')

    print(">> Hello")
    await wait()
    print(">> Who are you?")
    await wait()
    # 仅执行获取姓名的逻辑
    return_value = await data()
    print(f">> Nice to meet you {return_value}!")
    await wait()

    ask = input(">> would you like to create a user? y/n ")
    if ask == 'y':
        # 用户确认后再执行创建用户逻辑
        user, password  = await create_user()
        # 修正f字符串插值
        print(f">> Nice, you have a username {user} and a password {password}")
        await wait()
        print(">> now you are part of us!")
    else:
        print(">> You can not interact with me if you don't have a user")
        await wait()
        print(">> See you!")
        return

async def data(): # 获取用户姓名
    name = input(">> What's your name? ")
    return name
    

async def create_user(): # 获取用户账号信息
    user = input(">> Tell me a user name you like: ")
    passw = input(">> Now tell me a password: ")
    await wait()
    print(">> User created!")
    return user, passw
    

# 运行程序
asyncio.run(welcome())

内容的提问来源于stack exchange,提问作者Emmanuel Ramírez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:18:17