Repository navigation
Open
Labels
Description
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
foregroundAlso, 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 loopReading
ipython/docs/source/whatsnew/version7.rst
Lines 113 to 117 in 73d6335
| 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
tkf commentedon Sep 12, 2018
I should've continued reading a bit more:
ipython/docs/source/whatsnew/version7.rst
Lines 135 to 139 in 73d6335
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?(I don't know if
asyncio.sleepis compatible with other loop runners. If not, maybe add a method toloop_runnerand do appropriatesleep(0)? Also, if you are only targetingasyncioI guessprompt_toolkit.eventloop.use_asyncio_event_loopwould be the best option? But then supportingcurioandtriowould 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]:tkf commentedon Sep 12, 2018
... though I guess above example works nicely because I used
printinside the coroutine (so thatprompt_toolkittries to re-draw the prompt and then re-initiate the inputhook)?If I run:
messagesdoes not fill up after 10 sec unless I type something.Carreau commentedon Sep 12, 2018
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:>>> asyncio.create_taskdoes not run in aloop.Actually the second one is done on purpose for people wanting to manipulate
loopthemselve.I'm pretty sure the following will work:
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
runmethod, 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.)
tkf commentedon Sep 12, 2018
Thanks for the detailed explanation! Yes, allowing non-
awaitstatement to be eventloop-free seems to be a nice feature to have.I wanted is to run the following in
load_ipython_extension: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).
Carreau commentedon Sep 14, 2018
We pushed more docs here, les me know if that's clearer.
tkf commentedon Sep 14, 2018
Yes, it clarifies my question. Thanks a lot!
BTW, reading Internals section, I cannot help trying
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 :)Carreau commentedon Sep 14, 2018
Gah... good catch. I'm not sure we'll try to fix this one which seem to be miss-labeled as async indeed: