##// END OF EJS Templates
Merge pull request #11990 from jonathanslenders/asyncio-inputhook-improvements...
Matthias Bussonnier -
r25287:4352b6b4 merge
parent child Browse files
Show More
@@ -1,43 +1,46 b''
1 1 """
2 2 Inputhook for running the original asyncio event loop while we're waiting for
3 3 input.
4 4
5 5 By default, in IPython, we run the prompt with a different asyncio event loop,
6 6 because otherwise we risk that people are freezing the prompt by scheduling bad
7 7 coroutines. E.g., a coroutine that does a while/true and never yield back
8 8 control to the loop. We can't cancel that.
9 9
10 10 However, sometimes we want the asyncio loop to keep running while waiting for
11 11 a prompt.
12 12
13 13 The following example will print the numbers from 1 to 10 above the prompt,
14 14 while we are waiting for input. (This works also because we use
15 15 prompt_toolkit`s `patch_stdout`)::
16 16
17 17 In [1]: import asyncio
18 18
19 19 In [2]: %gui asyncio
20 20
21 21 In [3]: async def f():
22 22 ...: for i in range(10):
23 23 ...: await asyncio.sleep(1)
24 24 ...: print(i)
25 25
26 26
27 27 In [4]: asyncio.ensure_future(f())
28 28
29 29 """
30 30 import asyncio
31 31
32 32 # Keep reference to the original asyncio loop, because getting the event loop
33 33 # within the input hook would return the other loop.
34 34 loop = asyncio.get_event_loop()
35 35
36 36
37 37 def inputhook(context):
38 38 def stop():
39 39 loop.stop()
40 40
41 loop.add_reader(context.fileno(), stop)
42 context.fileno()
43 loop.run_forever()
41 fileno = context.fileno()
42 loop.add_reader(fileno, stop)
43 try:
44 loop.run_forever()
45 finally:
46 loop.remove_reader(fileno)
General Comments 0
You need to be logged in to leave comments. Login now