Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling IPython.embed() in asynchronous code (specifying the event loop)

Tags:

python

ipython

IPython 7.5 documentation states:

Change to Nested Embed

The introduction of the ability to run async code had some effect on the IPython.embed() API. By default, embed will not allow you to run asynchronous code unless an event loop is specified.

However, there seem to be no description how to specify the event loop, in the documentation.

Running:

import IPython
IPython.embed()

and then

In [1]: %autoawait on

In [2]: %autoawait
IPython autoawait is `on`, and set to use `<function _pseudo_sync_runner at 0x00000000066DEF28>`

In [3]: import asyncio

In [4]: await asyncio.sleep(1)

Gives:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
~\Envs\[redacted]\lib\site-packages\IPython\core\async_helpers.py in _pseudo_sync_runner(coro)
     71         # TODO: do not raise but return an execution result with the right info.
     72         raise RuntimeError(
---> 73             "{coro_name!r} needs a real async loop".format(coro_name=coro.__name__)
     74         )
     75

RuntimeError: 'run_cell_async' needs a real async loop

On the other hand, running:

import IPython
IPython.embed(using='asyncio')

and then:

In [1]: %autoawait on

In [2]: %autoawait
IPython autoawait is `on`, and set to use `asyncio`

In [3]: import asyncio

In [4]: await asyncio.sleep(1)

Gives:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
~\Envs\[redacted]\lib\site-packages\IPython\core\async_helpers.py in __call__(self, coro)
     25         import asyncio
     26
---> 27         return asyncio.get_event_loop().run_until_complete(coro)
     28
     29     def __str__(self):

c:\python35-64\Lib\asyncio\base_events.py in run_until_complete(self, future)
    452         future.add_done_callback(_run_until_complete_cb)
    453         try:
--> 454             self.run_forever()
    455         except:
    456             if new_task and future.done() and not future.cancelled():

c:\python35-64\Lib\asyncio\base_events.py in run_forever(self)
    406         self._check_closed()
    407         if self.is_running():
--> 408             raise RuntimeError('This event loop is already running')
    409         if events._get_running_loop() is not None:
    410             raise RuntimeError(

RuntimeError: This event loop is already running
```
like image 993
overflo Avatar asked Jun 02 '19 13:06

overflo


1 Answers

from IPython import embed
import nest_asyncio
nest_asyncio.apply()

Then embed(using='asyncio') might somewhat work. I don't know why they don't give us a real solution though.

like image 67
HappyFace Avatar answered Sep 21 '22 17:09

HappyFace