##// END OF EJS Templates
First draft of new kernel registry machinery...
Thomas Kluyver -
Show More
@@ -0,0 +1,72 b''
1 import io
2 import json
3 import os
4
5 pjoin = os.path.join
6
7 from IPython.utils.path import get_ipython_dir
8 from IPython.utils.py3compat import PY3
9 from IPython.utils.traitlets import HasTraits, List, Unicode
10
11 USER_KERNEL_DIR = pjoin(get_ipython_dir(), 'kernels')
12
13 if os.name == 'nt':
14 programdata = os.environ.get('PROGRAMDATA', None)
15 if programdata:
16 SYSTEM_KERNEL_DIR = pjoin(programdata, 'ipython', 'kernels')
17 else: # PROGRAMDATA is not defined by default on XP.
18 SYSTEM_KERNEL_DIR = None
19 else:
20 SYSTEM_KERNEL_DIR = "/usr/share/ipython/kernels"
21
22 NATIVE_KERNEL_NAME = 'python3' if PY3 else 'python2'
23
24 class KernelSpec(HasTraits):
25 argv = List()
26 display_name = Unicode()
27 language = Unicode()
28 codemirror_mode = Unicode()
29
30 resource_dir = Unicode()
31
32 def __init__(self, resource_dir, argv, display_name, language,
33 codemirror_mode=None):
34 super(KernelSpec, self).__init__(resource_dir=resource_dir, argv=argv,
35 display_name=display_name, language=language,
36 codemirror_mode=codemirror_mode)
37 if not self.codemirror_mode:
38 self.codemirror_mode = self.language
39
40 @classmethod
41 def from_resource_dir(cls, resource_dir):
42 kernel_file = os.path.join(resource_dir, 'kernel.json')
43 with io.open(kernel_file, 'r', encoding='utf-8') as f:
44 kernel_dict = json.load(f)
45 return cls(resource_dir=resource_dir, **kernel_dict)
46
47 def _is_kernel_dir(path):
48 return os.path.isdir(path) and os.path.isfile(pjoin(path, 'kernel.json'))
49
50 def _list_kernels_in(dir):
51 if dir is None:
52 return {}
53 return {f.lower(): pjoin(dir, f) for f in os.listdir(dir)
54 if _is_kernel_dir(pjoin(dir, f))}
55
56 def list_kernel_specs():
57 """Returns a dict mapping kernels to resource directories."""
58 d = _list_kernels_in(SYSTEM_KERNEL_DIR)
59 d.update(_list_kernels_in(USER_KERNEL_DIR))
60
61 if NATIVE_KERNEL_NAME not in d:
62 d[NATIVE_KERNEL_NAME] = '' # TODO: native kernel resource directory
63 return d
64
65 def get_kernel_spec(kernel_name):
66 """Returns a KernelSpec instance for the given kernel_name.
67
68 Raises KeyError if the given kernel name is not found.
69 """
70 d = list_kernel_specs()
71 resource_dir = d[kernel_name.lower()]
72 return KernelSpec.from_resource_dir(resource_dir) No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now