如何在非异步函数中使用 Await?

Asf*_*raa 12 python discord discord.py

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

我尝试过使用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))
Run Code Online (Sandbox Code Playgroud)

小智 2

需要import asyncio

\n

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

\n
    \n
  • asyncio.run() 函数运行顶级入口点 \xe2\x80\x9cmain()\xe2\x80\x9d\n 函数(请参阅上面的示例。)
  • \n
  • 正在等待协程。以下代码片段将在等待 1 秒后打印 \n\xe2\x80\x9chello\xe2\x80\x9d,然后再等待 2 秒后打印 \xe2\x80\x9cworld\xe2\x80\x9d:
  • \n
\n

例子

\n
import asyncio\nimport time\n\nasync def say_after(delay, what):\n    await asyncio.sleep(delay)\n    print(what)\n\nasync def main():\n    print(f"started at {time.strftime(\'%X\')}")\n\n    await say_after(1, \'hello\')\n    await say_after(2, \'world\')\n\n    print(f"finished at {time.strftime(\'%X\')}")\n\nasyncio.run(main())\n
Run Code Online (Sandbox Code Playgroud)\n

输出

\n
started at 17:14:32\nhello\nworld\nfinished at 17:14:34\n
Run Code Online (Sandbox Code Playgroud)\n

详细信息在这里

\n