Skip to content

asyncio.ensure_future does not run until next await #11303

Open

Description

@tkf

I tried something like ipython/ipykernel#323 (comment) but it looks like "background" tasks are run only when await statement is executed?

Python 3.7.0 (default, Jul 15 2018, 10:44:58)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.0.0.dev -- An enhanced Interactive Python. Type '?' for help.

IPython profile: plain

In [1]: import asyncio
   ...:
   ...: async def aprint(*args):
   ...:     print(*args)
   ...:
   ...: asyncio.ensure_future(aprint("background future"))
Out[1]: <Task pending coro=<aprint() running at <ipython-input-1-c3f9a8264358>:3>>

In [2]:

In [2]:

In [2]: await aprint("foreground")
background future
foreground

Also, asyncio.create_task does not work:

In [3]: asyncio.create_task(aprint("background task"))
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-3-6787ab5b49b6> in <module>
----> 1 asyncio.create_task(aprint("background task"))

/usr/lib64/python3.7/asyncio/tasks.py in create_task(coro)
    318     Return a Task object.
    319     """
--> 320     loop = events.get_running_loop()
    321     return loop.create_task(coro)
    322

RuntimeError: no running event loop

Reading

Non-Asynchronous code
~~~~~~~~~~~~~~~~~~~~~
As the internal API of IPython are now asynchronous, IPython need to run under
an even loop. In order to allow many workflow, (like using the ``%run`` magic,

I thought the event loop is always running. But it's not the case, right?

In [4]: asyncio.get_event_loop()
Out[4]: <_UnixSelectorEventLoop running=False closed=False debug=False>

In [5]: async def print_loop():
   ...:     print(asyncio.get_event_loop())

In [6]: await print_loop()
<_UnixSelectorEventLoop running=True closed=False debug=False>

I was expecting running=True in Out[4].

Checked with 73d6335

Activity

  1. tkf commented on Sep 12, 2018

    @tkf
    ContributorAuthor

    I should've continued reading a bit more:

    Expected Future changes
    ~~~~~~~~~~~~~~~~~~~~~~~
    We expect more internal but public IPython function to become ``async``, and
    will likely end up having a persisting event loop while IPython is running.

    which implies that event loop is not persistent at the moment.


    But it's still useful if I can run "background" tasks. Maybe not in the REPL, but I'm thinking in terms of IPython extensions. Yes, I know it does not run in parallel, only concurrently. The usecase I have in mind is pyjulia which has to execute code in the main thread to avoid segfault. In general, I think it is useful for interacting with non- therad-safe libraries concurrently.

    To run "background" tasks, how about just running a "tick" in inputhook?

    diff --git a/IPython/terminal/interactiveshell.py b/IPython/terminal/interactiveshell.py
    index 35cb06978..bf07c8a0d 100644
    --- a/IPython/terminal/interactiveshell.py
    +++ b/IPython/terminal/interactiveshell.py
    @@ -1,5 +1,6 @@
     """IPython terminal interface using prompt_toolkit"""
    
    +import asyncio
     import os
     import sys
     import warnings
    @@ -485,6 +486,8 @@ def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
         def inputhook(self, context):
             if self._inputhook is not None:
                 self._inputhook(context)
    +        if self.loop_runner:
    +            self.loop_runner(asyncio.sleep(0))
    
         active_eventloop = None
         def enable_gui(self, gui=None):
    

    (I don't know if asyncio.sleep is compatible with other loop runners. If not, maybe add a method to loop_runner and do appropriate sleep(0)? Also, if you are only targeting asyncio I guess prompt_toolkit.eventloop.use_asyncio_event_loop would be the best option? But then supporting curio and trio would become impossible?)

    Anyway, with the above change, background tasks can run:

    In [1]: import asyncio
       ...:
       ...:
       ...: async def repeat(msg, n):
       ...:     for i in range(n):
       ...:         print(f"{msg} {i}")
       ...:         await asyncio.sleep(1)
       ...:     return f"{msg} done"
       ...:
       ...: asyncio.ensure_future(repeat("background", 10))
    Out[1]: <Task pending coro=<repeat() running at <ipython-input-1-07ccbef816cf>:4>>
    
    background 0
    background 1
    background 2
    background 3
    background 4
    background 5
    In [2]:
    
    background 6
    background 7
    background 8
    background 9
    In [2]:
  2. tkf commented on Sep 12, 2018

    @tkf
    ContributorAuthor

    ... though I guess above example works nicely because I used print inside the coroutine (so that prompt_toolkit tries to re-draw the prompt and then re-initiate the inputhook)?

    If I run:

    import asyncio
    
    messages = []
    
    async def repeat(msg, n):
        for i in range(n):
            messages.append(f"{msg} {i}")
            await asyncio.sleep(1)
        messages.append.append(f"{msg} done")
    
    asyncio.ensure_future(repeat("background", 10))

    messages does not fill up after 10 sec unless I type something.

  3. modified the milestones: 7.1, 7.0 on Sep 12, 2018
  4. Carreau commented on Sep 12, 2018

    @Carreau
    Member

    Thanks for testing and the in-depth review and trying to understand how it work.

    Yes, one of the current limitation is that a loop get created/stopped for each execution. This is because we do some weird things with prompt_toolkit (actually starting and stopping prompt_toolkit in between each exec. So:

    • background task are not processed.
    • non async code >>> asyncio.create_task does not run in aloop.

    Actually the second one is done on purpose for people wanting to manipulate loop themselve.

    I'm pretty sure the following will work:

    >>> await asyncio.sleep(0)
    ... asyncio.create_task(aprint("background task"))
    

    It will force the thing to run in a loop.

    I'm guessing we would move toward always running a loop, so once IPython kernel 5.0 is out, you can try some of these features in notebook (or Jupyter-console) and see if it fixes (some) of the problem.

    We'll have to figure out trio/curio, but for now in ipykernel, we just block on their run method, be we could likely find a way to interleave tasks of asyncio and trio/curio.

    I'm temptatively marking this as 7.0 (for more docs), but I think we'll stay with current limitation for 7.0 because async support is way overdue.

    (We're also pushing to have async-exec in core Python in 3.8 if possible, to not have all these crazy hacks.)

  5. tkf commented on Sep 12, 2018

    @tkf
    ContributorAuthor

    Thanks for the detailed explanation! Yes, allowing non-await statement to be eventloop-free seems to be a nice feature to have.

    so once IPython kernel 5.0 is out, you can try some of these features in notebook (or Jupyter-console) and see if it fixes (some) of the problem

    I wanted is to run the following in load_ipython_extension:

    async def polling_julia():
        from julia.Base import sleep
        while True:
            sleep(0)
            await asyncio.sleep(0.05)
    
    
    if asyncio.get_event_loop().is_running():  # if in ipykernel
        asyncio.ensure_future(polling_julia())

    It seems that this works in ipykernel master.

    For this purpose, it would be nice if inputhook is implemented using event loop. It seems like many (but not all) inputhooks are implemented as polling in normal blocking functions. If they were async coroutines then multiple inputhooks can be run concurrently. Then I guess IPython can provide an API to register async coroutines as inputhooks. But this is more like a different feature request so I'll open another issue later (so that it can be fixed when the documentation is improved).

  6. Carreau commented on Sep 14, 2018

    @Carreau
    Member

    We pushed more docs here, les me know if that's clearer.

  7. modified the milestones: 7.0, 7.1 on Sep 14, 2018
  8. tkf commented on Sep 14, 2018

    @tkf
    ContributorAuthor

    Yes, it clarifies my question. Thanks a lot!

    BTW, reading Internals section, I cannot help trying

    In [1]: x = 1
       ...: def f():
       ...:     nonlocal x
       ...:     x = 10000

    which """should""" cause SyntaxError, I guess (which does happen in IPython 6 and also at module level). Though I don't think it matters in practice. If Python devs ask for a hundred reasons why they need async-exec maybe you can include it :)

  9. Carreau commented on Sep 14, 2018

    @Carreau
    Member

    Gah... good catch. I'm not sure we'll try to fix this one which seem to be miss-labeled as async indeed:

    In [1]: x = 1
       ...: import asyncio
       ...: loop = asyncio.get_event_loop()
       ...: def f():
       ...:     nonlocal x
       ...:     x = 10000
       ...: loop
    Out[1]: <_UnixSelectorEventLoop running=True closed=False debug=False>
    
  10. removed this from the 7.1 milestone on Oct 24, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions