当我调用函数send_message
时,我收到以下错误。
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/usr/lib/python3.4/threading.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "/home/joffe/Documents/discord/irc/ircbot.py", line 44, in get_message
mydiscord.send_message(line[1])
File "/home/joffe/Documents/discord/irc/mydiscord.py", line 37, in send_message
client.loop.run_until_complete(client.send_message(SERVER,message))
File "/usr/lib/python3.4/asyncio/base_events.py", line 331, in run_until_complete
self.run_forever()
File "/usr/lib/python3.4/asyncio/base_events.py", line 296, in run_forever
raise RuntimeError('Event loop is running.')
RuntimeError: Event loop is running.
我的函数send_message
收到一条消息并将其发送到不和谐频道。
该函数是从一个在线程中运行的函数调用的。客户端对象在主线程中创建。
def send_message(message):
print(str.encode("Message to discord: " + message))
client.loop.run_until_complete(client.send_message(SERVER,message))
答案 0 :(得分:15)
当我在已经运行的循环上调用loop.run_until_complete
时,我只看到“事件循环正在运行”异常(在另一个线程中,也许?)
如果循环已在另一个线程中运行,并且您想提交协程以执行它,请使用:
asyncio.run_coroutine_threadsafe(client.send_message(SERVER, message), client.loop)
如果你试图在循环中添加一个协同程序并且该循环正在当前线程上运行,那么最好的方法可能只是await
/ yield from
它,但如果你是从同步函数调度它,然后你可能想要:
asyncio.ensure_future(
client.send_message(SERVER, message),
loop=client.loop
).add_done_callback(fn)
其中fn
是一个函数,其唯一参数是由ensure_future
创建的未来,并在未来完成后调用。