run Python asyncio code in a Jupyter notebook

 

New Jupyter lab/notebook

import asyncio
import time

async def my_coroutine():  
    await asyncio.sleep(1)  
    print("Coroutine executed!")

s = time.perf_counter()
loop = asyncio.get_event_loop()
loop.create_task(my_coroutine())
asyncio.run_coroutine_threadsafe(my_coroutine(), loop)
asyncio.gather(my_coroutine())
elapsed = time.perf_counter() - s
print(f"Script executed in {elapsed:0.2f} seconds.")

  

Modern Jupyter lab/notebook

async def main():
    print(1)  
await main()

  

posted @ 2024-04-03 22:00  zyip  阅读(2)  评论(0编辑  收藏  举报