Last active
March 17, 2022 17:10
-
-
Save blink1073/4289a9393880b5d3e74b to your computer and use it in GitHub Desktop.
Xonsh Jupyter Metakernel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import absolute_import | |
from metakernel import MetaKernel | |
from xonsh.shell import Shell | |
import builtins | |
from xonsh import imphooks | |
import re | |
__version__ = '0.0' | |
version_pat = re.compile(r'version (\d+(\.\d+)+)') | |
class XonshMetaKernel(MetaKernel): | |
implementation = 'xonsh_kernel' | |
implementation_version = __version__ | |
language = 'python' | |
language_info = { | |
# 'mimetype': 'text/x-python', | |
# 'language': 'python', | |
# ------ If different from 'language': | |
# 'codemirror_mode': 'language', | |
# 'pygments_lexer': 'language', | |
# 'file_extension': 'py', | |
} | |
@property | |
def language_version(self): | |
m = version_pat.search(self.banner) | |
return m.group(1) | |
_banner = "XonSh" | |
@property | |
def banner(self): | |
return self._banner | |
def __init__(self, **kwargs): | |
MetaKernel.__init__(self, **kwargs) | |
self.repr = str | |
self.xshell = Shell(ctx={}) | |
self.env = builtins.__xonsh_env__ | |
self.env['XONSH_INTERACTIVE'] = False | |
def do_execute_direct(self, code): | |
self.payload = [] | |
if not code.strip(): | |
self.kernel_resp = {'status': 'ok', | |
'execution_count': self.execution_count, | |
'payload': [], 'user_expressions': {}} | |
return | |
shell = self.xshell | |
code = code if code.endswith('\n') else code + '\n' | |
try: | |
code = shell.execer.compile(code, mode='single', glbs=shell.ctx) | |
except TypeError: | |
code = '$(%s)\n' % code.strip() | |
code = shell.execer.compile(code, mode='single', glbs=shell.ctx) | |
output = shell.execer.eval(code, glbs=shell.ctx) | |
self.kernel_resp = {'status': 'ok', | |
'execution_count': self.execution_count, | |
'payload': [], 'user_expressions': {}} | |
return output | |
if __name__ == '__main__': | |
from IPython.kernel.zmq.kernelapp import IPKernelApp | |
IPKernelApp.launch_instance(kernel_class=XonshMetaKernel) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment