gpt4 book ai didi

python - Python3.x RuntimeError:事件循环已关闭

转载 作者:行者123 更新时间:2023-11-28 21:36:17 25 4
gpt4 key购买 nike

我在用aiohttp/asyncio做一些错误的事情。当我试图从循环中的另一个文件调用run_my_job()时,如果我只运行一次,那么下面的代码可以正常工作:

main.py
========================================
count = 0
batch_count = math.ceil((abc.get_count()/100))
print("there are {} batches to complete.".format(batch_count))
while count < batch_count:
print("starting batch {}...".format(count))
abc.run_my_job()
print("batch {} completed...".format(count))
count += 1


abc.py
===============================
def run_my_job(self):
self.queue_manager(self.do_stuff(all_the_tasks))

def queue_manager(self, method):
print('starting event queue')
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(method)
loop.run_until_complete(future)
loop.close()

async def async_post(self, resource, session, data):
async with session.post(self.api_attr.api_endpoint + resource, headers=self.headers, data=data) as response:
resp = await response.read()
return resp

async def do_stuff(self, data):
print('queueing tasks')

tasks = []
async with aiohttp.ClientSession() as session:
for row in data:
task = asyncio.ensure_future(self.async_post('my_api_endpoint', session, row))
tasks.append(task)
result = await asyncio.gather(*tasks)
self.load_results(result)
# goes on to load_results() method that parses json and updates the DB.

我得到这些错误:
Traceback (most recent call last):
File "C:/usr/PycharmProjects/api_framework/api_framework.py", line 37, in <module>
starting event queue
abc.run_my_job()
File "C:\usr\PycharmProjects\api_framework\api\abc\abc.py", line 77, in run_eligibility
self.queue_manager(self.verify_eligibility(json_data))
File "C:\usr\PycharmProjects\api_framework\api\abc\abc.py", line 187, in queue_manager
future = asyncio.ensure_future(method)
File "C:\Python36x64\lib\asyncio\tasks.py", line 512, in ensure_future
task = loop.create_task(coro_or_future)
File "C:\Python36x64\lib\asyncio\base_events.py", line 282, in create_task
self._check_closed()
File "C:\Python36x64\lib\asyncio\base_events.py", line 357, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'Consumer.run_my_job' was never awaited

最佳答案

看看这个函数:

def queue_manager(self, method):
print('starting event queue')
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(method)
loop.run_until_complete(future)
loop.close()

这就是你安排每项工作的方式。在函数的末尾,关闭事件循环。所以,在第一个作业运行之后,关闭事件循环。
如果在那之后尝试运行更多的作业,显然是在尝试在一个封闭的事件循环中运行它们。(而且您有运行其他作业的作业。)因此出现错误:
RuntimeError: Event loop is closed

只要去掉 loop.close(),问题就解决了。
我不确定这是否足够让你的程序工作,因为你还没有给我们一个可运行的例子,另外,在你的真实代码中, run_my_job显然是一个协同过程,但它不在你在这里发布的代码中。我看不出你在文章中还有其他明显的错误,但我不知道这有多重要。

关于python - Python3.x RuntimeError:事件循环已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51271477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com