asyncio.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """
  2. Inputhook for running the original asyncio event loop while we're waiting for
  3. input.
  4. By default, in IPython, we run the prompt with a different asyncio event loop,
  5. because otherwise we risk that people are freezing the prompt by scheduling bad
  6. coroutines. E.g., a coroutine that does a while/true and never yield back
  7. control to the loop. We can't cancel that.
  8. However, sometimes we want the asyncio loop to keep running while waiting for
  9. a prompt.
  10. The following example will print the numbers from 1 to 10 above the prompt,
  11. while we are waiting for input. (This works also because we use
  12. prompt_toolkit`s `patch_stdout`)::
  13. In [1]: import asyncio
  14. In [2]: %gui asyncio
  15. In [3]: async def f():
  16. ...: for i in range(10):
  17. ...: await asyncio.sleep(1)
  18. ...: print(i)
  19. In [4]: asyncio.ensure_future(f())
  20. """
  21. def inputhook(context):
  22. """
  23. Inputhook for asyncio event loop integration.
  24. """
  25. # For prompt_toolkit 3.0, this input hook literally doesn't do anything.
  26. # The event loop integration here is implemented in `interactiveshell.py`
  27. # by running the prompt itself in the current asyncio loop. The main reason
  28. # for this is that nesting asyncio event loops is unreliable.
  29. return