Methods run_until_complete https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_until_complete, run_forever https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_forever, run_in_executor https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_in_executor, create_task https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.create_task, call_at https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.call_at明确检查
循环并在关闭时抛出异常。
引用自文档 -BaseEvenLoop.close https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.close:
这是幂等的并且不可逆转的
除非你有一些(充分的)理由,否则你可以简单地省略结束行:
def scrape(category, field, pages, search, use_proxy, proxy_file):
#...
loop = asyncio.get_event_loop()
to_do = [ get_pages(url, params, conngen) for url in urls ]
wait_coro = asyncio.wait(to_do)
res, _ = loop.run_until_complete(wait_coro)
#...
# loop.close()
return [ x.result() for x in res ]
如果你想每次都有一个全新的循环,你不必手动创建它并设置为默认值:
def scrape(category, field, pages, search, use_proxy, proxy_file):
#...
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
to_do = [ get_pages(url, params, conngen) for url in urls ]
wait_coro = asyncio.wait(to_do)
res, _ = loop.run_until_complete(wait_coro)
#...
return [ x.result() for x in res ]