【问题标题】:Runtime error: Event loop is running运行时错误:事件循环正在运行
【发布时间】:2017-02-06 19:38:30
【问题描述】:

调用函数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))

【问题讨论】:

    标签: python-3.x python-asyncio


    【解决方案1】:

    “事件循环正在运行”异常表明您在已经运行的循环上调用了loop.run_until_complete,可能在另一个线程中。

    1. 如果循环已经在在另一个线程中运行并且你想提交一个协程让它执行,使用:

      asyncio.run_coroutine_threadsafe(client.send_message(SERVER, message), client.loop)
      
    2. 如果您尝试向循环中添加协程并且该循环正在在当前线程上运行,那么最好的方法可能就是 await/yield from

    3. 如果您从 同步函数 调度它,那么您 可能想要:

      asyncio.ensure_future(
          client.send_message(SERVER, message),
          loop=client.loop
      ).add_done_callback(fn)
      

      其中fn 是一个函数,其唯一参数是由ensure_future 创建的future,并在future 完成后调用。

    【讨论】:

      猜你喜欢
      • 2022-10-30
      • 2022-11-25
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2019-02-09
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多