简体   繁体   English

多线程 python 时的运行时错误“运行时错误:线程 'Thread-1' 中没有当前事件循环。”

[英]RuntimeError when multithreading python "RuntimeError: There is no current event loop in thread 'Thread-1'."

I am trying to run multiple discord bots with the same script at once.我正在尝试使用相同的脚本一次运行多个不和谐机器人。 The way I am doing this is going down a csv file, to get the bot token and bot name.我这样做的方法是下载一个 csv 文件,以获取机器人令牌和机器人名称。 I then start my script:然后我开始我的脚本:

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()

But then I get this error:但是后来我收到了这个错误:

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'.

Does anyone have any ideas on how I could fix it?有没有人对我如何解决它有任何想法?

You don't need to start a separate thread for each bot, the asyncio event loop is perfectly capable of serving all bots at once.您不需要为每个机器人启动一个单独的线程,asyncio 事件循环完全能够同时为所有机器人提供服务。 (That's the kind of thing event loops are designed for.) (这就是事件循环的设计目的。)

You just need to start all the bots as coroutines of the same asyncio event loop:您只需要将所有机器人作为同一个 asyncio 事件循环的协程启动:

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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RuntimeError: 线程 'Thread-1' 中没有当前事件循环,多线程和异步错误 - RuntimeError: There is no current event loop in thread 'Thread-1' , multithreading and asyncio error /accounts/register/ 处的 RuntimeError 线程 'Thread-1' 中没有当前事件循环 - RuntimeError at /accounts/register/ There is no current event loop in thread 'Thread-1' python龙卷风websocket错误:RuntimeError:线程'Thread-1'中没有当前事件循环 - python tornado websocket error: RuntimeError: There is no current event loop in thread 'Thread-1' requests-html“RuntimeError:在 flask 端点上使用时,线程‘Thread-1’中没有当前事件循环 - requests-html "RuntimeError: There is no current event loop in thread 'Thread-1' when using it on a flask endpoint RuntimeError: There is no current event loop in thread … DiscordPy MultiThreading - RuntimeError: There is no current event loop in thread … DiscordPy MultiThreading RuntimeError:线程“ Thread-1”中没有当前事件循环。 -request_html,html.render() - RuntimeError: There is no current event loop in thread 'Thread-1'. - requests_html, html.render() 我不知道如何解决以下错误; RuntimeError:线程“Thread-1”和“Thread-2”中没有当前事件循环 - I don't know how to fix the following error; RuntimeError: There is no current event loop in thread 'Thread-1' and 'Thread-2' RuntimeError:线程'Dummy-1'中没有当前事件循环 - RuntimeError: There is no current event loop in thread 'Dummy-1' RuntimeError:线程“MainThread”中没有当前事件循环 - RuntimeError: There is no current event loop in thread 'MainThread' Pytest:运行时错误线程“主线程”中没有当前事件循环 - Pytest: runtimeerror there is no current event loop in thread 'mainthread'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM