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

hyp*_*hen 2 python python-asyncio aiohttp python-3.6

我在用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.
Run Code Online (Sandbox Code Playgroud)

我得到这些错误:

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
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 5

看一下这个功能:

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()
Run Code Online (Sandbox Code Playgroud)

这就是您计划每个作业的要求。并且,在函数末尾,您将关闭事件循环。因此,在第一个作业运行后,您将关闭事件循环。

如果此后尝试运行更多作业,则显然是在封闭事件循环上运行它们。(并且您有可以运行更多作业的作业。)因此,出现错误:

RuntimeError: Event loop is closed
Run Code Online (Sandbox Code Playgroud)

只需删除loop.close(),该问题就会消失。

我不确定这是否足以使您的程序正常运行,因为您没有给我们提供任何可运行示例的信息,而且在您的真实代码中,run_my_job显然是协程,但不在您发布的代码中这里。在您发布的内容中,我没有看到其他任何明显的错误,但是我不知道这意味着什么。

  • @hyphen您确实想关闭循环,但是在程序结束时,在完成所有作业之后,而不是在完成每个作业之后。 (2认同)