2016-09-28 55 views
7

當我調用函數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)) 

回答

6

我只看過「事件循環運行的」例外當我打電話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創建和未來完成後,被稱爲未來。