2017-05-13 8 views
11

私はPythonを使ってdiscordのボットを書きたいと思っています。私はそれを実行しようとしたときPython [非合法の構文] with async def

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 

なぜですか?私はそれを前に受けたことがありませんでした。

+0

関数定義の前に 'async'を使用するのは、Python 3.4以降でのみ有効なシンタックです。 –

+0

はい私は "python3 1.py"を使ってスクリプトを実行しています – Andy

+0

だから、Python 3.4以上のものは動作するはずですか?私のサーバーが何とか夜間にPythonのバージョンを変更したので、それは本当に奇妙です:P – Andy

答えて

11

asyncおよびawaitのキーワードは、のPython 3.5以降でのみ有効です。です。あなたはそれよりも低い他のPythonのバージョンを使用している場合は、次の変更を行う必要があります。

  1. ではなくasync声明のコルーチンデコレータを使用します。

async def func(): 
    ... 

# replace with 

@asyncio.coroutine 
def func(): 
    ... 
  1. awaitの代わりにyield fromを使用してください。
ここで

... 
await coroutine() 
... 

# replace with 

... 
yield from coroutine() 
... 

あなたの機能は以前の構文を使用して、に変更するために必要なものの一例である:

@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の新しいバージョンでサポートされますが、それはあります古いバージョンをサポートする必要がない場合は、awaitasyncを使用することをお勧めします。あなたはこのdocumentationに戻って参照することができ、ここでの短い抜粋です:

コルーチンのasync defタイプはPython 3.5で追加されました、そして古いPythonのバージョンをサポートする必要がない場合 がお勧めです。