Python:“无法关闭正在运行的事件循环” Asyncio

时间:2018-11-02 22:36:30

标签: python loops twitter web-scraping python-asyncio

import asyncio
import Twper

async def main():
    q = Query('Some Query Goes Here', limit=20)
    async for tw in q.get_tweets():
        # Process data
        print(tw)


loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
    loop.run_until_complete(loop.shutdown_asyncgens())
finally:
    loop.close()

运行它时,我收到消息:

  

文件“ C:\ Users \ Anaconda3 \ lib \ asyncio \ selector_events.py”,第94行,在   关       引发RuntimeError(“无法关闭正在运行的事件循环”)

我该怎么办,才能正确使用Twper并抓取推文?

1 个答案:

答案 0 :(得分:1)

您必须先停止运行循环,然后才能关闭它。尝试做:

loop.stop()
time.sleep(1)
loop.close()