使用async def的Python [语法无效]

时间:2017-05-13 01:48:25

标签: python syntax async-await discord discord.py

我正在尝试使用Python编写discord机器人,我遇到了这个机器人。

import discord
import asyncio
import random

client = discord.Client()
inEmail = input("Email:")
inPassword = input("Passwd:")

async def background_loop():
    await client.wait_until_ready()
    while not client.is_closed:
        channel = client.get_channel("************")
        messages = ["Hello!", "How are you doing?", "Testing!!"]
        await client.send_message(channel, random.choice(messages))
        await asyncio.sleep(120)

client.loop.create_task(background_loop())
client.run(inEmail, inPassword)

然而,当我尝试运行它时,我收到了SyntaxError

File "1.py", line 7
  async def background_loop():
     ^
SyntaxError: invalid syntax

为什么?我测试之前从未收到过。

3 个答案:

答案 0 :(得分:37)

Asynchronous requests were introduced to Python in v3.3,如果您在v3.3(包括v2.X)之前运行Python,则必须安装较新版本的Python。

如果您运行的是Python 3.3:asyncio不属于stdlib,you'll need to install it manually from pypi

pip install asyncio

asyncawait关键字仅适用于Python 3.5或更高版本。如果您使用的是Python 3.3或3.4,则需要对代码进行以下更改:

  1. 使用@asyncio.coroutine装饰器代替async语句:
  2. async def func():
        pass
    
    # replace to:
    
    @asyncio.coroutine
    def func():
        pass
    
    1. 使用yield from代替await
    2. await coroutine() 
      
      # replace to:
      
      yield from coroutine()
      

      以下是您的功能需要更改的示例(如果您在3.3-3.4上):

      import asyncio
      
      @asyncio.coroutine 
      def background_loop():
          yield from client.wait_until_ready()
          while not client.is_closed:
              channel = client.get_channel("************")
              messages = ["Hello!", "How are you doing?", "Testing!!"]
              yield from client.send_message(channel, random.choice(messages))
              yield from asyncio.sleep(120)
      

      在较新版本的Python 3中仍然支持上述语法,但如果不需要支持Python 3.3-3.4,建议使用awaitasync。您可以参考此documentation,这是一个简短的片段:

        

      在Python 3.5中添加了async def类型的协程,并且是   如果不需要支持旧的Python版本,建议使用。

      除了:

      目前支持3.4.2-3.6.6,(它不支持3.3-3.4.1,截至2019年1月的3.7 )。

      对于使用discord.py进行开发,我建议使用discord.py重写分支:

      支持3.5.3-3.7。

答案 1 :(得分:3)

从3.7版开始 asyncawait是保留关键字

喜欢下图中的错误。

enter image description here

复制并打开路径(无__init__.py)。 您将获得一个.py文件列表 enter image description here

async.py重命名为_async.py或您想要的任何名称,因为从版本3.7开始,异步已成为我们的保留关键字。

重命名后,请在各处修改新名称。

*注意 虽然这不是永久性的解决方案 但是在出现相同语法错误的情况下它对我有用 在使用Firebase时。 最好的解决方案是使用早期版本的Python。即3.7以下的版本。

答案 2 :(得分:0)

我通过从github安装更新的PyMC来解决了这一问题(他们纠正了Python 3.7中发生的错误):

pip install git+https://github.com/pymc-devs/pymc.git