代码之家  ›  专栏  ›  技术社区  ›  The Bic Pen

如何正确地执行协同程序

  •  0
  • The Bic Pen  · 技术社区  · 7 年前

    我正在编写一个Discord bot,在测试异步函数时遇到了问题。我想用 exec()

    我已经尝试过exec()——在有等待和没有等待的情况下调用函数。我已经看过了 API docs ,但这并没有让我对我的问题有太多的了解。使用 eval() ,它返回coroutine对象,但不执行它。

    exec()是通过使用异步函数处理消息来完成的

    async def f(message)
        #other stuff
        ...
        ...
        exec(strip2(message.content, "exec"))
        return #exec doesn't return anything, so we return to not send an empty message
    

    异步函数如下所示:

    async def move_message(message_id, old_channel, new_channel):
        """
        check the 20 latest messages in old_channel, and if
        one of them matches the id, move it to new_channel
        """
        print("ok")
        async for message in old_channel.history(limit=20):
            #do stuff
            ...
        print("good!")
    

    如果没有等待,则会出现以下错误: ...\commands.py:1: RuntimeWarning: coroutine 'move_message' was never awaited 随着等待,它给了我一个机会 SyntaxError

     File "<string>", line 1
        await move_message(message, message.channel, "admin-test-playground")
                         ^
    SyntaxError: invalid syntax
    

    我希望函数能够正确执行,至少打印一些东西。但既不是“好”也不是“好!”用我现在的指纹。

    0 回复  |  直到 7 年前
        1
  •  2
  •   Edward Minnix    7 年前

    async await 有特殊的语法。 await expr async def 上下文。所以呢 exec("await function()") 将提出 SyntaxError exec 通过解析语句并运行它来操作,因此它不尊重事件循环。

    因此,您不能使用 等待 比函数调用更能改变代码的行为。

    但是,如果你改用 eval 执行 .

    def f(message):
        await eval(message.lstrip('exec '))
    

    让它正常工作。