0

I am trying to run a snippet of my code in Jupyter notebook, but it's failing. However the same snippet runs as script as well as a python script.

code :


import asyncio

async def a_square(x):
    print(f'Asynchronously squaring {x}!')
    return x ** 2


asyncio.run(a_square(2))

Error in Jupyter

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-4-e2feaf9936d2> in <module>
      5     return x ** 2
      6 
----> 7 asyncio.run(a_square(2))

/usr/lib/python3.8/asyncio/runners.py in run(main, debug)
     31     """
     32     if events._get_running_loop() is not None:
---> 33         raise RuntimeError(
     34             "asyncio.run() cannot be called from a running event loop")
     35 

RuntimeError: asyncio.run() cannot be called from a running event loop

Python path, version are same for all. The following statements gave same output for Jupyter, Ipython as well as when executed from script.

import sys
print(sys.executable)
print(sys.version)

output :

/usr/bin/python3
3.8.5 (default, Jul 27 2020, 08:42:51) 
[GCC 10.1.0]
patel deven
  • 630
  • 7
  • 9
  • 1
    Here's a better answer. https://stackoverflow.com/a/55409674/12479639 Basically as the error states, Jupyter is already running an event loop and you need only to `await` your function. – Axe319 Aug 18 '20 at 14:54
  • It seems like Jupyter is already running an event loop of it's own then. For the new ascynio, the asyncio.run removes the necessity of creating a new loop, something which i wanted to try. – patel deven Aug 19 '20 at 07:38

0 Answers0