1
我正在使用discord.py与不和谐进行交互。从Python中的非协议函数运行协程函数?
def hi():
await client.send_message(channel, message)
得到语法错误,除非我在hi()函数中写入“async”。 我真的不明白这一点,请帮助!
我正在使用discord.py与不和谐进行交互。从Python中的非协议函数运行协程函数?
def hi():
await client.send_message(channel, message)
得到语法错误,除非我在hi()函数中写入“async”。 我真的不明白这一点,请帮助!
您可以在事件循环中安排协程。你不能在非协程中调用它们或等待它们。
让我们来看看下面的代码:
import asyncio
async def greetLater(name, delay):
await asyncio.sleep(delay)
print("Hello {}!".format(name))
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(greetLater("masnun", 10))
if __name__ == '__main__':
main()
在上面的代码,greetLater
是一个协同程序。我们不能直接从main
函数中调用它。我们在这里需要做的是创建一个事件循环,然后在那里安排协程。我们使用asyncio
模块来帮助我们创建事件循环并运行协程。
更多参考:
http://masnun.com/2015/11/13/python-generators-coroutines-native-coroutines-and-async-await.html
http://masnun.com/2015/11/20/python-asyncio-future-task-and-the-event-loop.html
(免责声明:链接的话题我的个人博客文章,你可以谷歌更多的参考资料)
传递循环到它所在的函数中可以关闭吗?我所做的可能会被其他人使用,我认为你比我更有经验。 – apoorlydrawnape
我没有完全理解这个场景,但是通常传递循环没问题。 – masnun