【问题标题】:RuntimeError when multithreading python "RuntimeError: There is no current event loop in thread 'Thread-1'."多线程 python 时的 RuntimeError “RuntimeError:线程 'Thread-1' 中没有当前事件循环。”
【发布时间】:2021-02-20 07:27:23
【问题描述】:

我正在尝试一次使用相同的脚本运行多个不和谐机器人。我这样做的方式是下载一个 csv 文件,以获取机器人令牌和机器人名称。然后我开始我的脚本:

import time, csv, re, random, string, sys, os, asyncio
from datetime import datetime
from threading import Thread
import discord
from dotenv import load_dotenv
from discord_webhook import DiscordWebhook, DiscordEmbed

def main(bottoken, botname):
    TOKEN = (bottoken)
    client = discord.Client()

    @client.event
    async def on_ready():
        print(f'{client.user.name} has connected to Discord!')

    @client.event
    async def on_message(message):
         #do stuff
         print('Do stuff')

    client.run(TOKEN)

def runtask():

    if __name__ == '__main__':
        with open('botinfo.csv', 'r') as f:
            reader = csv.reader(f, delimiter=',')
            for i, row in enumerate(reader):
                Thread(target = main, args=(row[0], row[1])).start()

if __name__ == '__main__':
    runtask()

然后我得到这个错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/alexforman/Documents/GitHub/bot-price-monitor/frontend_multithread.py", line 14, in main
    client = discord.Client()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 216, in __init__
    self.loop = asyncio.get_event_loop() if loop is None else loop
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/alexforman/Documents/GitHub/bot-price-monitor/frontend_multithread.py", line 14, in main
    client = discord.Client()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 216, in __init__
    self.loop = asyncio.get_event_loop() if loop is None else loop
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-2'.

有人对我如何解决它有任何想法吗?

【问题讨论】:

    标签: python multithreading python-asyncio


    【解决方案1】:

    您不需要为每个机器人启动单独的线程,异步事件循环完全能够同时为所有机器人提供服务。 (这就是事件循环的设计目的。)

    您只需将所有机器人作为同一个异步事件循环的协程启动:

    async def run_client(bottoken, botname):
        TOKEN = (bottoken)
        client = discord.Client()
    
        @client.event
        async def on_ready():
            print(f'{client.user.name} has connected to Discord!')
    
        @client.event
        async def on_message(message):
             #do stuff
             print('Do stuff')
    
        # can't use client.run() because it would block the event loop
        # but we can use client.start(), which is a coroutine that does
        # the same thing (and which is internally called by client.run)
        await client.start(TOKEN)
    
    async def main():
        coros = []
        with open('botinfo.csv', 'r') as f:
            reader = csv.reader(f, delimiter=',')
            for i, row in enumerate(reader):
                coros.append(run_client(row[0], row[1]))
        await asyncio.gather(*coros)
    
    if __name__ == '__main__':
        asyncio.run(main())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多