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