【问题标题】:How can I use Await in a non async function?如何在非异步函数中使用 Await?
【发布时间】:2021-03-05 20:23:29
【问题描述】:

我正在开发一个不和谐的机器人并试图解决这个问题。我想知道如果我可以在代码的最后一行的 lambda 行中等待一个函数,我该如何在非异步函数中使用 await。

我尝试过使用 player 变量执行 asyncio.run,我也尝试过 asyncio.run_coroutine_threadsafe,但没有成功。

关于如何使它工作的任何想法?

代码:

def queue_check(self, ctx):
    global queue_list
    global loop
    global playing


    if loop is True:
        queue_list.append(playing)
    elif loop is False:
        playing = ''

    if ctx.channel.last_message.content == '$skip' or '$s':
        return

    song = queue_list.pop(0)
    player = await YTDLSource.from_url(song, loop=self.client.loop, stream=True)

    
    ctx.voice_client.play(player, after= queue_check(self,ctx))





    @commands.command(aliases=['p'])
    @commands.guild_only()
    async def play(self, ctx, *, url):
        global queue_list
        global playing
            
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                return await ctx.send("> You are not connected to a voice channel.")



        async with ctx.typing():
                
            player = await YTDLSource.from_url(url, loop=self.client.loop, stream=True)
            await ctx.send(f'> :musical_note: Now playing: **{player.title}** ')
            
            playing = url


            await ctx.voice_client.play(player, after=lambda e: queue_check(self,ctx))

【问题讨论】:

  • 你不能。任何使用await 的函数都必须定义为async

标签: python discord discord.py


【解决方案1】:

需要import asyncio

为了实际运行协程,asyncio 提供了三种主要机制:

  • 运行顶级入口点“main()”的 asyncio.run() 函数 函数(见上面的例子)
  • 等待协程。以下 sn-p 代码将打印 等待1秒后“hello”,然后打印“world” 再等 2 秒:

示例

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

输出

started at 17:14:32
hello
world
finished at 17:14:34

详情here

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 2020-03-09
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多