python - Python3.x RuntimeError:事件循环已关闭
问题描述
我在 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
显然是一个协程,但它不在您发布的代码中这里。我在您发布的内容中没有看到任何其他明显的错误,但我不知道这意味着什么。
推荐阅读
- amazon-web-services - 如何使用 API-Gateway 作为服务代理直接调用 DynamoDB Scan API?
- html - Tailwind h-screen 在移动设备上无法正常工作
- arrays - 数组处理 VBA
- python - selenium driver.get() 是否被视为自动化和“非人类”的东西?
- spring-boot - 如何在spring boot中将用户定义的网页url映射到特定的html?
- java - 如何在 try/catch 中设置布尔标记并获取结果
- python - 每天从累积总和计算
- java - JavaFX setCellValueFactory 无法检索属性 IllegalAcessException
- android - 如何使用 Firebase 实时数据库持久性来存储节点的一些子节点
- data-binding - UWP 中的数据绑定