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

And*_*ndy 31 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)
Run Code Online (Sandbox Code Playgroud)

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

File "1.py", line 7
  async def background_loop():
     ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

这是为什么?我测试之前从未收到过.

abc*_*ccd 39

异步请求是在v3.3中引入Python的,如果你在v3.3(包括v2.X)之前运行Python,你将不得不安装更新版本的Python.


只有当你运行Python 3.3:asyncio不是stdlib的一部分时,你需要从pypi手动安装它:

pip install asyncio
Run Code Online (Sandbox Code Playgroud)

asyncawait关键字是唯一有效的Python 3.5或更高版本.如果您使用的是Python 3.3或3.4,则需要对代码进行以下更改:

  1. 使用@asyncio.coroutine装饰器而不是async语句:

async def func():
    pass

# replace to:

@asyncio.coroutine
def func():
    pass
Run Code Online (Sandbox Code Playgroud)
  1. 使用yield from而不是await:

await coroutine() 

# replace to:

yield from coroutine()
Run Code Online (Sandbox Code Playgroud)

以下是您的函数需要更改的示例(如果您使用的是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)
Run Code Online (Sandbox Code Playgroud)

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

async def在Python 3.5中添加了协同程序的类型,如果不需要支持较旧的Python版本,建议使用它.


在旁边:

目前支持3.4.2-3.6.6,(它不支持3.3-3.4.1,3.7为2019一月).

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

discord.py 支持3.5.3-3.7.


小智 7

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

就像下图中的错误。

在此处输入图片说明

复制并打开路径(不带__init__.py)。您将获得 .py 文件列表 在此处输入图片说明

重命名async.py_async.py或任何您想要的名称,因为 async 现在是我们从 3.7 版开始的保留关键字。

重命名后,随处修改新名称。

*注意虽然它不是一个永久性的解决方案,但它对我有用,以防在使用 firebase 时出现相同的语法错误。最好的解决方案是使用以前版本的 Python。即低于 3.7 的版本。