带有 async def 的 Python [无效语法]

标签 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

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

最佳答案

2021 年的更新答案(discord.py 1.x - 2.x):

discord.py 目前支持 Python 3.5 及更高版本。如果您收到 SyntaxError,则表示您使用的是旧版本的 Python,并且不被 discord.py 支持。

首先,安装更高版本的 Python(在此消息中首选 3.8.x),然后运行 ​​python3.8 bot.pypy -3.8 bot.py(适用于 Windows)。注意:安装时不要忘记选择“Add Python to PATH”。


原答案

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


在您运行 Python 3.3 时:asyncio 不是标准库的一部分,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 语句:
async def func():
    pass

# replace to:

@asyncio.coroutine
def func():
    pass
  1. 使用 yield from 而不是 await:
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 ,这是一个简短的片段:

The async def type of coroutine was added in Python 3.5, and is recommended if there is no need to support older Python versions.


旁白:

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

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

支持3.5.3-3.7。

关于带有 async def 的 Python [无效语法],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43948454/

相关文章:

python - 使用 gobject.timeout_add_seconds - 段错误

c - 在C中,node.next->prev与node->next->prev相同吗?

c# - 如何在 PropertyValidator 重写的 IsValid 中等待方法?

c# - 什么情况下等待取消的任务会抛出TaskCanceledException?

python - TensorFlow v2 替换 clip_gradients_by_norm

python - 在多个标签中多次更改图像的最佳方法是什么?

python - 将 Pandas 数据框的第一行转换为列名

powershell - 什么是@”运算符?

c - 在c中初始化一个新结构

c# - 有效返回 "Task<Task<MyObject>>"吗?或者最好返回 "Task.FromResult(MyObject)"