Debian Codegraph @

examples/embedding/inprocess_terminal.py

raw
1 """An in-process terminal example."""
2
3 import os
4 import sys
5
6 import tornado
7 from jupyter_console.ptshell import ZMQTerminalInteractiveShell
8
9 from ipykernel.inprocess.manager import InProcessKernelManager
10
11
12 def print_process_id():
13 """Print the process id."""
14 print("Process ID is:", os.getpid())
15
16
17 def init_asyncio_patch():
18 """set default asyncio policy to be compatible with tornado
19 Tornado 6 (at least) is not compatible with the default
20 asyncio implementation on Windows
21 Pick the older SelectorEventLoopPolicy on Windows
22 if the known-incompatible default policy is in use.
23 do this as early as possible to make it a low priority and overridable
24 ref: https://github.com/tornadoweb/tornado/issues/2608
25 FIXME: if/when tornado supports the defaults in asyncio,
26 remove and bump tornado requirement for py38
27 """
28 if (
29 sys.platform.startswith("win")
30 and sys.version_info >= (3, 8)
31 and tornado.version_info < (6, 1)
32 ):
33 import asyncio
34
35 try:
36 from asyncio import WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy
37 except ImportError:
38 pass
39 # not affected
40 else:
41 if type(asyncio.get_event_loop_policy()) is WindowsProactorEventLoopPolicy:
42 # WindowsProactorEventLoopPolicy is not compatible with tornado 6
43 # fallback to the pre-3.8 default of Selector
44 asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())
45
46
47 def main():
48 """The main function."""
49 print_process_id()
50
51 # Create an in-process kernel
52 # >>> print_process_id()
53 # will print the same process ID as the main process
54 init_asyncio_patch()
55 kernel_manager = InProcessKernelManager()
56 kernel_manager.start_kernel()
57 kernel = kernel_manager.kernel
58 kernel.gui = "qt4"
59 kernel.shell.push({"foo": 43, "print_process_id": print_process_id})
60 client = kernel_manager.client()
61 client.start_channels()
62
63 shell = ZMQTerminalInteractiveShell(manager=kernel_manager, client=client)
64 shell.mainloop()
65
66
67 if __name__ == "__main__":
68 main()