为什么在使用 threading.Thread() 时出现 RuntimeError?

Why am I getting RuntimeError while using threading.Thread()?

今天又是提问日。我正在 python 中处理请求,我正在尝试加快处理速度。如果你还记得的话,我已经问过一个关于这个的问题。今天我完成了那个代码,然后继续面对类似的问题。

运行 此代码生成 RuntimeError。它说:

RuntimeError: There is no current event loop in thread 'Thread-2'

我不知道为什么会出现此错误,因为我使用的是 threading.Thread() 而不是 asyncio。为什么要求事件循环?

def func(mininum, maximum=None):
    if maximum == None:
        maximum = mininum
    import asyncio
    import aiohttp
    from bs4 import BeautifulSoup


    async def find_account(i_d, session):
        try:
            async with session.get(f'https://web.roblox.com/users/{i_d}/profile') as response:
                if response.status == 200:
                    r = await response.read()
                    soup = BeautifulSoup(r, 'html.parser')
                    stuff = list(soup.find_all('h2'))
                    stuff = stuff[0]
                    stuff = list(stuff)
                    stuff = stuff[0]

                    print(f'{i_d} is done')
                    return str(stuff) + ' ID: {id}'.format(id=i_d)

                else:
                    return 'None'
        except aiohttp.ServerDisconnectedError:
            await find_account(i_d, session)
        except asyncio.exceptions.TimeoutError:
            await find_account(i_d, session)


    async def id_range(minimum, maximum):
        tasks = []
        async with aiohttp.ClientSession() as session:
            for i in range(minimum, maximum + 1):
                tasks.append(asyncio.create_task(find_account(i_d=i, session=session)))

            return await asyncio.gather(*tasks)


    event_loop = asyncio.get_event_loop()
    return event_loop.run_until_complete(id_range(mininum, maximum))








import threading

all = []

p1 = threading.Thread(target=func, args=(1,1000)).start()
p2 = threading.Thread(target=func, args=(1001,2000)).start()

p1 : threading.Thread
p2 : threading.Thread
p1.join()
p2.join()```


#Comment if you need more traceback.

使用线程时不能使用 async/await 关键字。 相反,OS 将自动决定何时切换线程。