I have the following code:
async def fetch(session, url):
video_id = url.split('/')[-2]
async with session.get(url) as response:
data = await response.text()
async with aiofiles.open(f'{video_id}.json', 'w') as f:
await f.write(data)
async def main(loop, urls):
async with aiohttp.ClientSession(loop=loop) as session:
tasks = [fetch(session, url) for url in urls]
await asyncio.gather(*tasks)
if __name__ == '__main__':
links = generate_links()
loop = asyncio.get_event_loop()
await main(loop, links)
The script runs smoothly in the Jupyter notebook but it won't run from within a .py script due to SyntaxError: 'await' outside function.
I'm trying to understand what is happening here and why this is the case.
await main()should be changed toasyncio.run(main()), to run code successfully. docs.python.org/3/library/asyncio-task.htmlasyncio.run(main(loop, links))but it throws:RuntimeError: Timeout context manager should be used inside a taskasyncio), the reason being convenience.