首页 > 解决方案 > “运行直到完成”循环在功能完成后没有结束?

问题描述

我一直在开发一个 Discord 机器人,它从 Ubisoft 的 Rainbow Six Siege stats API 中提取信息。我是编码新手,我知道这有点麻烦,但是为了检索统计信息,我使用了我在API 文档中找到的一些示例代码:

    @types.coroutine
def run():
    auth = api.Auth("my_email", "my_password")
    player = yield from auth.get_player(username, api.Platforms.UPLAY)
    operator = yield from player.get_operator(oprtr)
    print(operator.kills)
    global result
    result = (operator.kills)

asyncio.get_event_loop().run_until_complete(run())

print (result)

我把它放在我创建的命令函数中:

@client.command()
async def wins(ctx, username, oprtr):
    print (username, oprtr)

其中一起给出了下面的代码,我对其进行了注释以显示循环如何不结束。@types.coroutine 本身(不在命令内)工作正常,只是当它在 @client.command() 内时,循环才不会结束。

@client.command()
async def wins(ctx, username, oprtr):
    print (username, oprtr)

    @types.coroutine
    def run():
        auth = api.Auth("my_email", "my_password")
        player = yield from auth.get_player(username, api.Platforms.UPLAY)
        operator = yield from player.get_operator(oprtr)
        print(operator.kills)     #this value prints, so the function definitely works.
        global result
        result = (operator.kills)

    asyncio.get_event_loop().run_until_complete(run()) #this is the loop which seems to never end,
                                                       #and blocks anything from progressing

    print (result)           #these two outputs do not send, which tells me that everything is being
    await ctx.send("Hello")  #blocked by the loop

正如我所说,我是一个相当新的和非常垃圾的编码器,所以我感谢任何帮助,这一直困扰着我!如果您需要更多信息,我会尽力为您提供。

标签: pythondiscorddiscord.py

解决方案


与其使用破坏直到完成循环,不如尝试循环直到某个变量为真或假。

notdone = true
while notdone == true:
    #do whatever in here and when you want it to finish, just set notdone to false.

推荐阅读