new jupiter intrface
This commit is contained in:
@@ -49,9 +49,13 @@
|
||||
|
||||
configure_file(setup.py.in ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
|
||||
|
||||
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources)
|
||||
file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png INPUT ${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png )
|
||||
file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png INPUT ${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png )
|
||||
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources )
|
||||
file( COPY ${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png
|
||||
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/ )
|
||||
file( RENAME ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/yap_32x32x32.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png )
|
||||
file( COPY ${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources )
|
||||
file( RENAME ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/yap_64x64x32.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png )
|
||||
file( COPY ${CMAKE_CURRENT_SOURCE_DIR}/kernel.js DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/ )
|
||||
file( COPY ${CMAKE_SOURCE_DIR}/misc/editors/prolog.js DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/)
|
||||
|
||||
set(SETUP_PY ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
|
||||
|
@@ -1,6 +1,10 @@
|
||||
#include COPYING.md
|
||||
#include CONTRIBUTING.md
|
||||
include README.md
|
||||
include yap_kernel/resources/logo-32x32.png
|
||||
include yap_kernel/resources/logo-64x64.png
|
||||
include yap_kernel/resources/kernel.js
|
||||
include yap_kernel/resources/kernel.json
|
||||
|
||||
|
||||
# Documentation
|
||||
|
0
packages/python/yap_kernel/__init__.py
Normal file
0
packages/python/yap_kernel/__init__.py
Normal file
@@ -14,6 +14,7 @@ name = 'yap_kernel'
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
import sys
|
||||
import sysconfig
|
||||
import setuptools
|
||||
|
||||
v = sys.version_info
|
||||
@@ -43,8 +44,10 @@ packages = setuptools.find_packages('${CMAKE_CURRENT_SOURCE_DIR}')
|
||||
# if os.path.exists(pjoin(d, '__init__.py')):
|
||||
# packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||
|
||||
sys.path.insert(0, "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
package_data = {
|
||||
'yap_kernel': ['resources/*.*','prolog/*.*'],
|
||||
'yap_ipython': ['prolog/*.*'],
|
||||
'yap_kernel': ['resources/*.*']
|
||||
}
|
||||
|
||||
|
||||
@@ -62,9 +65,9 @@ setup_args = dict(
|
||||
packages = packages,
|
||||
py_modules = ['yap_kernel_launcher'],
|
||||
package_data = package_data,
|
||||
package_dir = {'':"${CMAKE_CURRENT_SOURCE_DIR}" },
|
||||
package_dir = {'':"${CMAKE_CURRENT_SOURCE_DIR}"},
|
||||
description = "YAP Kernel for Jupyter",
|
||||
author = 'YP Development Team',
|
||||
author = 'YAP Development Team',
|
||||
author_email = 'YAP-dev@scipy.org',
|
||||
url = 'http://ipython.org',
|
||||
license = 'BSD',
|
||||
@@ -91,15 +94,26 @@ install_requires = setuptools_args['install_requires'] = [
|
||||
if any(a.startswith(('bdist', 'build', 'install')) for a in sys.argv):
|
||||
from yap_kernel.kernelspec import write_kernel_spec, make_yap_kernel_cmd, KERNEL_NAME
|
||||
|
||||
|
||||
argv = make_yap_kernel_cmd(executable='python')
|
||||
dest = os.path.join(here, 'data_kernelspec')
|
||||
dest = os.path.join(here, 'resources')
|
||||
if os.path.exists(dest):
|
||||
shutil.rmtree(dest)
|
||||
write_kernel_spec(dest, overrides={'argv': argv})
|
||||
|
||||
shutil.copy('${CMAKE_CURRENT_SOURCE_DIR}/kernel.js',dest)
|
||||
shutil.copy('${CMAKE_SOURCE_DIR}/misc/editors/prolog.js',dest)
|
||||
shutil.copy('${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png',os.path.join(dest,'logo-32x32.png'))
|
||||
shutil.copy('${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png',os.path.join(dest,'logo-64x64.png'))
|
||||
setup_args['data_files'] = [
|
||||
(pjoin('share', 'jupyter', 'kernels', KERNEL_NAME), glob(pjoin(dest, '*'))),
|
||||
]
|
||||
mode_loc = pjoin( sysconfig.get_path('platlib'), 'notebook', 'static', 'components', 'codemirror', 'mode', 'prolog')
|
||||
try:
|
||||
os.mkdir(mode_loc)
|
||||
except:
|
||||
pass
|
||||
shutil.copy( "${CMAKE_SOURCE_DIR}/misc/editors/prolog.js" , mode_loc)
|
||||
|
||||
|
||||
extras_require = setuptools_args['extras_require'] = {
|
||||
'test:python_version=="2.7"': ['mock'],
|
||||
|
@@ -0,0 +1,151 @@
|
||||
# encoding: utf-8
|
||||
"""
|
||||
IPython: tools for interactive and parallel computing in Python.
|
||||
|
||||
http://ipython.org
|
||||
"""
|
||||
#-----------------------------------------------------------------------------
|
||||
# Copyright (c) 2008-2011, IPython Development Team.
|
||||
# Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
|
||||
# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
|
||||
# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
|
||||
#
|
||||
# Distributed under the terms of the Modified BSD License.
|
||||
#
|
||||
# The full license is in the file COPYING.txt, distributed with this software.
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Imports
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Setup everything
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
# Don't forget to also update setup.py when this changes!
|
||||
if sys.version_info < (3,3):
|
||||
raise ImportError(
|
||||
"""
|
||||
IPython 6.0+ does not support Python 2.6, 2.7, 3.0, 3.1, or 3.2.
|
||||
When using Python 2.7, please install IPython 5.x LTS Long Term Support version.
|
||||
Beginning with IPython 6.0, Python 3.3 and above is required.
|
||||
|
||||
See IPython `README.rst` file for more information:
|
||||
|
||||
https://github.com/ipython/ipython/blob/master/README.rst
|
||||
|
||||
""")
|
||||
|
||||
# Make it easy to import extensions - they are always directly on pythonpath.
|
||||
# Therefore, non-IPython modules can be added to extensions directory.
|
||||
# This should probably be in ipapp.py.
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Setup the top level names
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
from .core.getipython import get_ipython
|
||||
from .core import release
|
||||
from IPython.core.application import Application
|
||||
from IPython.terminal.embed import embed
|
||||
|
||||
from .core.interactiveshell import YAPInteractive as InteractiveShell
|
||||
from IPython.testing import test
|
||||
from IPython.utils.sysinfo import sys_info
|
||||
from IPython.utils.frame import extract_module_locals
|
||||
|
||||
# Release data
|
||||
__author__ = '%s <%s>' % (release.author, release.author_email)
|
||||
__license__ = release.license
|
||||
__version__ = release.version
|
||||
version_info = release.version_info
|
||||
|
||||
def embed_kernel(module=None, local_ns=None, **kwargs):
|
||||
"""Embed and start an IPython kernel in a given scope.
|
||||
|
||||
If you don't want the kernel to initialize the namespace
|
||||
from the scope of the surrounding function,
|
||||
and/or you want to load full IPython configuration,
|
||||
you probably want `IPython.start_kernel()` instead.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
module : ModuleType, optional
|
||||
The module to load into IPython globals (default: caller)
|
||||
local_ns : dict, optional
|
||||
The namespace to load into IPython user namespace (default: caller)
|
||||
|
||||
kwargs : various, optional
|
||||
Further keyword args are relayed to the IPKernelApp constructor,
|
||||
allowing configuration of the Kernel. Will only have an effect
|
||||
on the first embed_kernel call for a given process.
|
||||
"""
|
||||
|
||||
(caller_module, caller_locals) = extract_module_locals(1)
|
||||
if module is None:
|
||||
module = caller_module
|
||||
if local_ns is None:
|
||||
local_ns = caller_locals
|
||||
|
||||
# Only import .zmq when we really need it
|
||||
from ipykernel.embed import embed_kernel as real_embed_kernel
|
||||
real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
|
||||
|
||||
def start_ipython(argv=None, **kwargs):
|
||||
"""Launch a normal IPython instance (as opposed to embedded)
|
||||
|
||||
`IPython.embed()` puts a shell in a particular calling scope,
|
||||
such as a function or method for debugging purposes,
|
||||
which is often not desirable.
|
||||
|
||||
`start_ipython()` does full, regular IPython initialization,
|
||||
including loading startup files, configuration, etc.
|
||||
much of which is skipped by `embed()`.
|
||||
|
||||
This is a public API method, and will survive implementation changes.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
|
||||
argv : list or None, optional
|
||||
If unspecified or None, IPython will parse command-line options from sys.argv.
|
||||
To prevent any command-line parsing, pass an empty list: `argv=[]`.
|
||||
user_ns : dict, optional
|
||||
specify this dictionary to initialize the IPython user namespace with particular values.
|
||||
kwargs : various, optional
|
||||
Any other kwargs will be passed to the Application constructor,
|
||||
such as `config`.
|
||||
"""
|
||||
from IPython.terminal.ipapp import launch_new_instance
|
||||
return launch_new_instance(argv=argv, **kwargs)
|
||||
|
||||
def start_kernel(argv=None, **kwargs):
|
||||
"""Launch a normal IPython kernel instance (as opposed to embedded)
|
||||
|
||||
`IPython.embed_kernel()` puts a shell in a particular calling scope,
|
||||
such as a function or method for debugging purposes,
|
||||
which is often not desirable.
|
||||
|
||||
`start_kernel()` does full, regular IPython initialization,
|
||||
including loading startup files, configuration, etc.
|
||||
much of which is skipped by `embed()`.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
|
||||
argv : list or None, optional
|
||||
If unspecified or None, IPython will parse command-line options from sys.argv.
|
||||
To prevent any command-line parsing, pass an empty list: `argv=[]`.
|
||||
user_ns : dict, optional
|
||||
specify this dictionary to initialize the IPython user namespace with particular values.
|
||||
kwargs : various, optional
|
||||
Any other kwargs will be passed to the Application constructor,
|
||||
such as `config`.
|
||||
"""
|
||||
from IPython.kernel.zmq.kernelapp import launch_new_instance
|
||||
return launch_new_instance(argv=argv, **kwargs)
|
||||
|
@@ -0,0 +1,20 @@
|
||||
#-----------------------------------------------------------------------------
|
||||
# Copyright (C) 2013 The IPython Development Team
|
||||
#
|
||||
# Distributed under the terms of the BSD License. The full license is in
|
||||
# the file COPYING, distributed as part of this software.
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Classes and functions
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_ipython():
|
||||
"""Get the global InteractiveShell instance.
|
||||
|
||||
Returns None if no InteractiveShell instance is registered.
|
||||
"""
|
||||
from yap_ipython.core.interactiveshell import YAPInteractive
|
||||
if YAPInteractive.initialized():
|
||||
return YAPInteractive.instance()
|
||||
|
397
packages/python/yap_kernel/yap_ipython/core/interactiveshell.py
Normal file
397
packages/python/yap_kernel/yap_ipython/core/interactiveshell.py
Normal file
@@ -0,0 +1,397 @@
|
||||
import os
|
||||
import sys
|
||||
import abc
|
||||
|
||||
import yap4py.yapi
|
||||
from IPython.core import interactiveshell
|
||||
from IPython.core.completer import IPCompleter
|
||||
from IPython.core.interactiveshell import ExecutionResult, InteractiveShell
|
||||
from IPython.utils.strdispatch import StrDispatch
|
||||
# import yap_ipython.core
|
||||
from traitlets import Instance
|
||||
|
||||
from pygments import highlight
|
||||
from pygments.lexers.prolog import PrologLexer
|
||||
from pygments.formatters import HtmlFormatter
|
||||
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
use_module = namedtuple('use_module', 'file')
|
||||
bindvars = namedtuple('bindvars', 'list')
|
||||
library = namedtuple('library', 'list')
|
||||
v = namedtuple('_', 'slot')
|
||||
load_files = namedtuple('load_files', 'file ofile args')
|
||||
python_query= namedtuple('python_query', 'query_mgr string')
|
||||
jupyter_query = namedtuple('jupyter_query', 'self string')
|
||||
enter_cell = namedtuple('enter_cell', 'self' )
|
||||
exit_cell = namedtuple('exit_cell', 'self' )
|
||||
completions = namedtuple('completions', 'txt self' )
|
||||
|
||||
class YAPCompleter:
|
||||
|
||||
def __init__(self, engine):
|
||||
self.yapeng = engine
|
||||
self.completions = None
|
||||
|
||||
def complete(self, text, line=None, cursor_pos=None):
|
||||
"""Return the completed text and a list of completions.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
|
||||
text : string
|
||||
A string of text to be completed on. It can be given as empty and
|
||||
instead a line/position pair are given. In this case, the
|
||||
completer itself will split the line like readline does.
|
||||
|
||||
line : string, optional
|
||||
The complete line that text is part of.
|
||||
|
||||
cursor_pos : int, optional
|
||||
The position of the cursor on the input line.
|
||||
|
||||
Returns
|
||||
-------
|
||||
text : string
|
||||
The actual text that was completed.
|
||||
|
||||
matches : list
|
||||
A sorted list with all possible completions.
|
||||
|
||||
The optional arguments allow the completion to take more context into
|
||||
account, and are part of the low-level completion API.
|
||||
|
||||
This is a wrapper around the completion mechanism, similar to what
|
||||
readline does at the command line when the TAB key is hit. By
|
||||
exposing it as a method, it can be used by other non-readline
|
||||
environments (such as GUIs) for text completion.
|
||||
|
||||
Simple usage example:
|
||||
|
||||
In [1]: x = 'hello'
|
||||
|
||||
In [2]: _ip.complete('x.l')
|
||||
Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
|
||||
"""
|
||||
|
||||
if not text:
|
||||
text = line[:cursor_pos]
|
||||
self.yapeng.goal(completions(text, self))
|
||||
return text, self.completions
|
||||
|
||||
# def _init__(self, **kwargs) -> None:
|
||||
# PyCompleter.__init__(**kwargs__)
|
||||
|
||||
|
||||
|
||||
class YAPInteractive(InteractiveShell):
|
||||
"""An enhanced, interactive shell for YAP."""
|
||||
|
||||
def init_yap_completer(self):
|
||||
"""Initialize the completion machinery.
|
||||
|
||||
This creates completion machinery that can be used by client code,
|
||||
either interactively in-process (typically triggered by the readline
|
||||
library), programmatically (such as in test suites) or out-of-process
|
||||
(typically over the network by remote frontends).
|
||||
"""
|
||||
print(self)
|
||||
|
||||
# Add custom completers to the basic ones built into IPCompleter
|
||||
self.Completer = YAPCompleter(self.yapeng)
|
||||
self.configurables.append(self.Completer)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(YAPInteractive, self).__init__(**kwargs)
|
||||
# type: (object, object) -> object
|
||||
pjoin = os.path.join
|
||||
here = os.path.dirname(__file__)
|
||||
self.yapeng = yap4py.yapi.Engine()
|
||||
self.yapeng.goal(use_module(pjoin(here, '../prolog/jupyter.yap')))
|
||||
self.q = None
|
||||
self.run = False
|
||||
self.os = ""
|
||||
self.port = None
|
||||
self.init_yap_completer()
|
||||
|
||||
def init_syntax_highlighting(self, changes=None):
|
||||
# Python source parser/formatter for syntax highlighting
|
||||
# pyformat = PyColorize.Parser(style=self.colors, parent=self).format
|
||||
# self.pycolorize = lambda src: pyformat(src,'str')
|
||||
self.pycolorize = lambda code : highlight(code, PrologLexer(), HtmlFormatter())
|
||||
|
||||
|
||||
|
||||
|
||||
def complete(self, text, line=None, cursor_pos=None):
|
||||
"""Return the completed text and a list of completions.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
|
||||
text : string
|
||||
A string of text to be completed on. It can be given as empty and
|
||||
instead a line/position pair are given. In this case, the
|
||||
completer itself will split the line like readline does.
|
||||
|
||||
line : string, optional
|
||||
The complete line that text is part of.
|
||||
|
||||
cursor_pos : int, optional
|
||||
The position of the cursor on the input line.
|
||||
|
||||
Returns
|
||||
-------
|
||||
text : string
|
||||
The actual text that was completed.
|
||||
|
||||
matches : list
|
||||
A sorted list with all possible completions.
|
||||
|
||||
The optional arguments allow the completion to take more context into
|
||||
account, and are part of the low-level completion API.
|
||||
|
||||
This is a wrapper around the completion mechanism, similar to what
|
||||
readline does at the command line when the TAB key is hit. By
|
||||
exposing it as a method, it can be used by other non-readline
|
||||
environments (such as GUIs) for text completion.
|
||||
|
||||
Simple usage example:
|
||||
|
||||
In [1]: x = 'hello'
|
||||
|
||||
In [2]: _ip.complete('x.l')
|
||||
Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
|
||||
"""
|
||||
|
||||
# Inject names into __builtin__ so we can complete on the added names.
|
||||
return self.Completer.complete(text, line, cursor_pos)
|
||||
|
||||
|
||||
|
||||
|
||||
def run_cell(self, raw_cell, store_history=True, silent=False,
|
||||
shell_futures=True):
|
||||
"""Run a complete IPython cell.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
raw_cell : str
|
||||
The code (including IPython code such as
|
||||
%magic functions) to run.
|
||||
store_history : bool
|
||||
If True, the raw and translated cell will be stored in IPython's
|
||||
history. For user code calling back into
|
||||
IPython's machinery, this
|
||||
should be set to False.
|
||||
silent : bool
|
||||
If True, avoid side-effects, such as implicit displayhooks and
|
||||
and logging. silent=True forces store_history=False.
|
||||
shell_futures : bool
|
||||
If True, the code will share future statements with the interactive
|
||||
shell. It will both be affected by previous
|
||||
__future__ imports, and any __future__ imports in the code
|
||||
will affect the shell. If False,
|
||||
__future__ imports are not shared in either direction.
|
||||
|
||||
Returns
|
||||
|
||||
-------
|
||||
|
||||
`result : :class:`ExecutionResult`
|
||||
"""
|
||||
|
||||
# construct a query from a one-line string
|
||||
# q is opaque to Python
|
||||
# vs is the list of variables
|
||||
# you can print it out, the left-side is the variable name,
|
||||
# the right side wraps a handle to a variable
|
||||
# pdb.set_trace()
|
||||
# #pdb.set_trace()
|
||||
# atom match either symbols, or if no symbol exists, strings, In this case
|
||||
# variable names should match strings
|
||||
# ask = True
|
||||
# launch the query
|
||||
result = ExecutionResult()
|
||||
|
||||
if (not raw_cell) or raw_cell.isspace():
|
||||
self.last_execution_succeeded = True
|
||||
return result
|
||||
|
||||
if silent:
|
||||
store_history = False
|
||||
|
||||
if store_history:
|
||||
result.execution_count = self.execution_count
|
||||
|
||||
def error_before_exec(value):
|
||||
result.error_before_exec = value
|
||||
self.last_execution_succeeded = False
|
||||
return result
|
||||
|
||||
self.events.trigger('pre_execute')
|
||||
if not silent:
|
||||
self.events.trigger('pre_run_cell')
|
||||
|
||||
# If any of our input transformation (input_transformer_manager or
|
||||
# prefilter_manager) raises an exception, we store it in this variable
|
||||
# so that we can display the error after logging the input and storing
|
||||
# it in the history.
|
||||
# preprocessing_exc_tuple = None
|
||||
# try:
|
||||
# # Static input transformations
|
||||
# cell = raw_cell #self.input_transformer_manager.transform_cell(raw_cell)
|
||||
# except SyntaxError:
|
||||
# preprocessing_exc_tuple = sys.exc_info()
|
||||
cell = raw_cell # cell has to exist so it can be stored/logged
|
||||
# else:
|
||||
# # import pdb; pdb.set_trace()
|
||||
# if False and len(cell.splitlines()) == 1:
|
||||
# # Dynamic transformations - only applied for single line commands
|
||||
# with self.builtin_trap:
|
||||
# try:
|
||||
# # use prefilter_lines to handle trailing newlines
|
||||
# # restore trailing newline for ast.parse
|
||||
# cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
|
||||
# except Exception:
|
||||
# # don't allow prefilter errors to crash IPython
|
||||
# preprocessing_exc_tuple = sys.exc_info()
|
||||
|
||||
|
||||
# Store raw and processed history
|
||||
if store_history:
|
||||
self.history_manager.store_inputs(self.execution_count,
|
||||
cell, raw_cell)
|
||||
if not silent:
|
||||
self.logger.log(cell, raw_cell)
|
||||
|
||||
# # Display the exception if input processing failed.
|
||||
# if preprocessing_exc_tuple is not None:
|
||||
# self.showtraceback(preprocessing_exc_tuple)
|
||||
# if store_history:
|
||||
# self.execution_count += 1
|
||||
# return error_before_exec(preprocessing_exc_tuple[2])
|
||||
|
||||
# Our own compiler remembers the __future__ environment. If we want to
|
||||
# run code with a separate __future__ environment, use the default
|
||||
# compiler
|
||||
# compiler = self.compile if shell_futures else CachingCompiler()
|
||||
|
||||
cell_name = str( self.execution_count)
|
||||
|
||||
if cell[0] == '%':
|
||||
if cell[1] == '%':
|
||||
linec = False
|
||||
mcell = cell.lstrip('%%')
|
||||
else:
|
||||
linec = True
|
||||
mcell = cell.lstrip('%')
|
||||
txt0 = mcell.split(maxsplit = 2, sep = '\n')
|
||||
txt = txt0[0].split(maxsplit = 2)
|
||||
magic = txt[0]
|
||||
if len(txt) == 2:
|
||||
line = txt[1]
|
||||
else:
|
||||
line = ""
|
||||
if linec:
|
||||
self.run_line_magic(magic, line)
|
||||
if len(txt0) == 2:
|
||||
cell = txt0[1]
|
||||
else:
|
||||
cellArea = ""
|
||||
else:
|
||||
self.run_cell_magic(magic, line, cell)
|
||||
return
|
||||
# Give the displayhook a reference to our ExecutionResult so it
|
||||
# can fill in the output value.
|
||||
self.displayhook.exec_result = result
|
||||
has_raised = False
|
||||
try:
|
||||
self.bindings = dict = {}
|
||||
state = self.jupyter_query(cell)
|
||||
if state:
|
||||
self.last_execution_succeeded = True
|
||||
result.result = (True, dict)
|
||||
else:
|
||||
self.last_execution_succeeded = True
|
||||
result.result = (True, {})
|
||||
except Exception as e:
|
||||
print(e)
|
||||
has_raised = True
|
||||
result.result = False
|
||||
|
||||
self.last_execution_succeeded = not has_raised
|
||||
|
||||
# Reset this so later displayed values do not modify the
|
||||
# ExecutionResult
|
||||
self.displayhook.exec_result = None
|
||||
print(self.complete)
|
||||
self.events.trigger('post_execute')
|
||||
if not silent:
|
||||
self.events.trigger('post_run_cell')
|
||||
|
||||
if store_history:
|
||||
# Write output to the database. Does nothing unless
|
||||
# history output logging is enabled.
|
||||
self.history_manager.store_output(self.execution_count)
|
||||
# Each cell is a *single* input, regardless of how many lines it has
|
||||
self.execution_count += 1
|
||||
|
||||
return result
|
||||
|
||||
def jupyter_query(self, s):
|
||||
# import pdb; pdb.set_trace()
|
||||
#
|
||||
# construct a self.query from a one-line string
|
||||
# self.q is opaque to Python
|
||||
self.bindings = {}
|
||||
self.port = "call"
|
||||
if self.q and s != self.os:
|
||||
self.q.close()
|
||||
self.q = None
|
||||
if not self.q:
|
||||
self.q = self.yapeng.query(jupyter_query(self, s))
|
||||
self.os = s
|
||||
# vs is the list of variables
|
||||
# you can print it out, the left-side is the variable name,
|
||||
# the right side wraps a handle to a variable
|
||||
# pdb.set_trace()
|
||||
# #pdb.set_trace()
|
||||
# atom match either symbols, or if no symbol exists, sttrings, In this case
|
||||
# variable names should match strings
|
||||
#for eq in vs:
|
||||
# if not isinstance(eq[0],str):
|
||||
# print( "Error: Variable Name matches a Python Symbol")
|
||||
# return
|
||||
# ask = True
|
||||
# launch the query
|
||||
# run the new command using the given tracer
|
||||
rc = self.answer(self.q)
|
||||
if rc:
|
||||
# deterministic = one solution
|
||||
if self.port == "exit":
|
||||
# done
|
||||
self.q.close()
|
||||
self.q = None
|
||||
self.os = ""
|
||||
print("yes")
|
||||
return True, self.bindings
|
||||
print("No (more) answers")
|
||||
self.q.close()
|
||||
self.q = None
|
||||
return True, None
|
||||
|
||||
def answer(self, q):
|
||||
try:
|
||||
return q.next()
|
||||
except Exception as e:
|
||||
print(e.args[1])
|
||||
self.yapeng.goal(exit_cell(self))
|
||||
return False, None
|
||||
|
||||
|
||||
class YAPInteractiveABC(metaclass=abc.ABCMeta):
|
||||
"""An abstract base class for YAPInteractive."""
|
||||
|
||||
YAPInteractiveABC.register(YAPInteractive)
|
13
packages/python/yap_kernel/yap_ipython/core/modulefind.py
Normal file
13
packages/python/yap_kernel/yap_ipython/core/modulefind.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from modulefinder import ModuleFinder
|
||||
|
||||
finder = ModuleFinder()
|
||||
finder.run_script('__main__.py')
|
||||
|
||||
print('Loaded modules:')
|
||||
for name, mod in finder.modules.items():
|
||||
print('%s: ' % name, end='')
|
||||
print(','.join(list(mod.globalnames.keys())[:3]))
|
||||
|
||||
print('-'*50)
|
||||
print('Modules not imported:')
|
||||
print('\n'.join(finder.badmodules.keys()))
|
118
packages/python/yap_kernel/yap_ipython/core/release.py
Normal file
118
packages/python/yap_kernel/yap_ipython/core/release.py
Normal file
@@ -0,0 +1,118 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Release data for the IPython project."""
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Copyright (c) 2008, IPython Development Team.
|
||||
# Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
|
||||
# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
|
||||
# Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
|
||||
#
|
||||
# Distributed under the terms of the Modified BSD License.
|
||||
#
|
||||
# The full license is in the file COPYING.txt, distributed with this software.
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
# Name of the package for release purposes. This is the name which labels
|
||||
# the tarballs and RPMs made by distutils, so it's best to lowercase it.
|
||||
name = 'ipython'
|
||||
|
||||
# IPython version information. An empty _version_extra corresponds to a full
|
||||
# release. 'dev' as a _version_extra string means this is a development
|
||||
# version
|
||||
_version_major = 0
|
||||
_version_minor = 1
|
||||
_version_patch = 0
|
||||
_version_extra = '.dev'
|
||||
# _version_extra = 'rc2'
|
||||
_version_extra = '' # Uncomment this for full releases
|
||||
|
||||
# Construct full version string from these.
|
||||
_ver = [_version_major, _version_minor, _version_patch]
|
||||
|
||||
__version__ = '.'.join(map(str, _ver))
|
||||
if _version_extra:
|
||||
__version__ = __version__ + _version_extra
|
||||
|
||||
version = __version__ # backwards compatibility name
|
||||
version_info = (_version_major, _version_minor, _version_patch, _version_extra)
|
||||
|
||||
# Change this when incrementing the kernel protocol version
|
||||
kernel_protocol_version_info = (5, 0)
|
||||
kernel_protocol_version = "%i.%i" % kernel_protocol_version_info
|
||||
|
||||
description = "IPython: Productive Interactive Computing"
|
||||
|
||||
long_description = \
|
||||
"""
|
||||
IPython provides a rich toolkit to help you make the most out of using Python
|
||||
interactively. Its main components are:
|
||||
|
||||
* A powerful interactive Python shell
|
||||
* A `Jupyter <http://jupyter.org/>`_ kernel to work with Python code in Jupyter
|
||||
notebooks and other interactive frontends.
|
||||
|
||||
The enhanced interactive Python shells have the following main features:
|
||||
|
||||
* Comprehensive object introspection.
|
||||
|
||||
* Input history, persistent across sessions.
|
||||
|
||||
* Caching of output results during a session with automatically generated
|
||||
references.
|
||||
|
||||
* Extensible tab completion, with support by default for completion of python
|
||||
variables and keywords, filenames and function keywords.
|
||||
|
||||
* Extensible system of 'magic' commands for controlling the environment and
|
||||
performing many tasks related either to IPython or the operating system.
|
||||
|
||||
* A rich configuration system with easy switching between different setups
|
||||
(simpler than changing $PYTHONSTARTUP environment variables every time).
|
||||
|
||||
* Session logging and reloading.
|
||||
|
||||
* Extensible syntax processing for special purpose situations.
|
||||
|
||||
* Access to the system shell with user-extensible alias system.
|
||||
|
||||
* Easily embeddable in other Python programs and GUIs.
|
||||
|
||||
* Integrated access to the pdb debugger and the Python profiler.
|
||||
|
||||
The latest development version is always available from IPython's `GitHub
|
||||
site <http://github.com/ipython>`_.
|
||||
"""
|
||||
|
||||
license = 'BSD'
|
||||
|
||||
authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'),
|
||||
'Janko' : ('Janko Hauser','jhauser@zscout.de'),
|
||||
'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
|
||||
'Ville' : ('Ville Vainio','vivainio@gmail.com'),
|
||||
'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
|
||||
'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'),
|
||||
'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'),
|
||||
'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'),
|
||||
'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'),
|
||||
}
|
||||
|
||||
author = 'The IPython Development Team'
|
||||
|
||||
author_email = 'ipython-dev@python.org'
|
||||
|
||||
url = 'https://ipython.org'
|
||||
|
||||
|
||||
platforms = ['Linux','Mac OSX','Windows']
|
||||
|
||||
keywords = ['Interactive','Interpreter','Shell', 'Embedding']
|
||||
|
||||
classifiers = [
|
||||
'Framework :: IPython',
|
||||
'Intended Audience :: Developers',
|
||||
'Intended Audience :: Science/Research',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
'Programming Language :: Python',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Topic :: System :: Shells'
|
||||
]
|
414
packages/python/yap_kernel/yap_ipython/core/shellapp.py
Normal file
414
packages/python/yap_kernel/yap_ipython/core/shellapp.py
Normal file
@@ -0,0 +1,414 @@
|
||||
# encoding: utf-8
|
||||
"""
|
||||
A mixin for :class:`~IPython.core.application.Application` classes that
|
||||
launch InteractiveShell instances, load extensions, etc.
|
||||
"""
|
||||
|
||||
# Copyright (c) IPython Development Team.
|
||||
# Distributed under the terms of the Modified BSD License.
|
||||
|
||||
import glob
|
||||
from itertools import chain
|
||||
import os
|
||||
import sys
|
||||
|
||||
from traitlets.config.application import boolean_flag
|
||||
from traitlets.config.configurable import Configurable
|
||||
from traitlets.config.loader import Config
|
||||
from IPython.core.application import SYSTEM_CONFIG_DIRS
|
||||
from IPython.core import pylabtools
|
||||
from IPython.utils.contexts import preserve_keys
|
||||
from IPython.utils.path import filefind
|
||||
from traitlets import (
|
||||
Unicode, Instance, List, Bool, CaselessStrEnum, observe,
|
||||
)
|
||||
from IPython.terminal import pt_inputhooks
|
||||
|
||||
ENV_CONFIG_DIRS = []
|
||||
_env_config_dir = os.path.join(sys.prefix, 'etc', 'ipython')
|
||||
if _env_config_dir not in SYSTEM_CONFIG_DIRS:
|
||||
# only add ENV_CONFIG if sys.prefix is not already included
|
||||
ENV_CONFIG_DIRS.append(_env_config_dir)
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Aliases and Flags
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
|
||||
|
||||
backend_keys = sorted(pylabtools.backends.keys())
|
||||
backend_keys.insert(0, 'auto')
|
||||
|
||||
shell_flags = {}
|
||||
|
||||
addflag = lambda *args: shell_flags.update(boolean_flag(*args))
|
||||
addflag('autoindent', 'YAPInteractive.autoindent',
|
||||
'Turn on autoindenting.', 'Turn off autoindenting.'
|
||||
)
|
||||
addflag('automagic', 'YAPInteractive.automagic',
|
||||
"""Turn on the auto calling of magic commands. Type %%magic at the
|
||||
IPython prompt for more information.""",
|
||||
'Turn off the auto calling of magic commands.'
|
||||
)
|
||||
addflag('pdb', 'YAPInteractive.pdb',
|
||||
"Enable auto calling the pdb debugger after every exception.",
|
||||
"Disable auto calling the pdb debugger after every exception."
|
||||
)
|
||||
addflag('pprint', 'PlainTextFormatter.pprint',
|
||||
"Enable auto pretty printing of results.",
|
||||
"Disable auto pretty printing of results."
|
||||
)
|
||||
addflag('color-info', 'YAPInteractive.color_info',
|
||||
"""IPython can display information about objects via a set of functions,
|
||||
and optionally can use colors for this, syntax highlighting
|
||||
source code and various other elements. This is on by default, but can cause
|
||||
problems with some pagers. If you see such problems, you can disable the
|
||||
colours.""",
|
||||
"Disable using colors for info related things."
|
||||
)
|
||||
nosep_config = Config()
|
||||
nosep_config.YAPInteractive.separate_in = ''
|
||||
nosep_config.YAPInteractive.separate_out = ''
|
||||
nosep_config.YAPInteractive.separate_out2 = ''
|
||||
|
||||
shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
|
||||
shell_flags['pylab'] = (
|
||||
{'YAPInteractiveApp' : {'pylab' : 'auto'}},
|
||||
"""Pre-load matplotlib and numpy for interactive use with
|
||||
the default matplotlib backend."""
|
||||
)
|
||||
shell_flags['matplotlib'] = (
|
||||
{'YAPInteractiveApp' : {'matplotlib' : 'auto'}},
|
||||
"""Configure matplotlib for interactive use with
|
||||
the default matplotlib backend."""
|
||||
)
|
||||
|
||||
# it's possible we don't want short aliases for *all* of these:
|
||||
shell_aliases = dict(
|
||||
autocall='YAPInteractive.autocall',
|
||||
colors='YAPInteractive.colors',
|
||||
logfile='YAPInteractive.logfile',
|
||||
logappend='YAPInteractive.logappend',
|
||||
c='YAPInteractiveApp.code_to_run',
|
||||
m='YAPInteractiveApp.module_to_run',
|
||||
ext='YAPInteractiveApp.extra_extension',
|
||||
gui='YAPInteractiveApp.gui',
|
||||
pylab='YAPInteractiveApp.pylab',
|
||||
matplotlib='YAPInteractiveApp.matplotlib',
|
||||
)
|
||||
shell_aliases['cache-size'] = 'YAPInteractive.cache_size'
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Main classes and functions
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
class YAPInteractiveApp(Configurable):
|
||||
"""A Mixin for applications that start YAPInteractive instances.
|
||||
|
||||
Provides configurables for loading extensions and executing files
|
||||
as part of configuring a Shell environment.
|
||||
|
||||
The following methods should be called by the :meth:`initialize` method
|
||||
of the subclass:
|
||||
|
||||
- :meth:`init_path`
|
||||
- :meth:`init_shell` (to be implemented by the subclass)
|
||||
- :meth:`init_gui_pylab`
|
||||
- :meth:`init_extensions`
|
||||
- :meth:`init_code`
|
||||
"""
|
||||
extensions = List(Unicode(),
|
||||
help="A list of dotted module names of IPython extensions to load."
|
||||
).tag(config=True)
|
||||
extra_extension = Unicode('',
|
||||
help="dotted module name of an IPython extension to load."
|
||||
).tag(config=True)
|
||||
|
||||
reraise_ipython_extension_failures = Bool(False,
|
||||
help="Reraise exceptions encountered loading IPython extensions?",
|
||||
).tag(config=True)
|
||||
|
||||
# Extensions that are always loaded (not configurable)
|
||||
default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
|
||||
|
||||
hide_initial_ns = Bool(True,
|
||||
help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
|
||||
be hidden from tools like %who?"""
|
||||
).tag(config=True)
|
||||
|
||||
exec_files = List(Unicode(),
|
||||
help="""List of files to run at IPython startup."""
|
||||
).tag(config=True)
|
||||
exec_PYTHONSTARTUP = Bool(True,
|
||||
help="""Run the file referenced by the PYTHONSTARTUP environment
|
||||
variable at IPython startup."""
|
||||
).tag(config=True)
|
||||
file_to_run = Unicode('',
|
||||
help="""A file to be run""").tag(config=True)
|
||||
|
||||
exec_lines = List(Unicode(),
|
||||
help="""lines of code to run at IPython startup."""
|
||||
).tag(config=True)
|
||||
code_to_run = Unicode('',
|
||||
help="Execute the given command string."
|
||||
).tag(config=True)
|
||||
module_to_run = Unicode('',
|
||||
help="Run the module as a script."
|
||||
).tag(config=True)
|
||||
gui = CaselessStrEnum(gui_keys, allow_none=True,
|
||||
help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
|
||||
).tag(config=True)
|
||||
matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
|
||||
help="""Configure matplotlib for interactive use with
|
||||
the default matplotlib backend."""
|
||||
).tag(config=True)
|
||||
pylab = CaselessStrEnum(backend_keys, allow_none=True,
|
||||
help="""Pre-load matplotlib and numpy for interactive use,
|
||||
selecting a particular matplotlib backend and loop integration.
|
||||
"""
|
||||
).tag(config=True)
|
||||
pylab_import_all = Bool(True,
|
||||
help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
|
||||
and an ``import *`` is done from numpy and pylab, when using pylab mode.
|
||||
|
||||
When False, pylab mode should not import any names into the user namespace.
|
||||
"""
|
||||
).tag(config=True)
|
||||
shell = Instance('yap_ipython.core.interactiveshell.YAPInteractiveABC',
|
||||
allow_none=True)
|
||||
# whether interact-loop should start
|
||||
interact = Bool(True)
|
||||
|
||||
user_ns = Instance(dict, args=None, allow_none=True)
|
||||
@observe('user_ns')
|
||||
def _user_ns_changed(self, change):
|
||||
if self.shell is not None:
|
||||
self.shell.user_ns = change['new']
|
||||
self.shell.init_user_ns()
|
||||
|
||||
def init_path(self):
|
||||
"""Add current working directory, '', to sys.path"""
|
||||
if sys.path[0] != '':
|
||||
sys.path.insert(0, '')
|
||||
|
||||
def init_shell(self):
|
||||
raise NotImplementedError("Override in subclasses")
|
||||
|
||||
def init_gui_pylab(self):
|
||||
"""Enable GUI event loop integration, taking pylab into account."""
|
||||
enable = False
|
||||
shell = self.shell
|
||||
if self.pylab:
|
||||
enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
|
||||
key = self.pylab
|
||||
elif self.matplotlib:
|
||||
enable = shell.enable_matplotlib
|
||||
key = self.matplotlib
|
||||
elif self.gui:
|
||||
enable = shell.enable_gui
|
||||
key = self.gui
|
||||
|
||||
if not enable:
|
||||
return
|
||||
|
||||
try:
|
||||
r = enable(key)
|
||||
except ImportError:
|
||||
self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
|
||||
self.shell.showtraceback()
|
||||
return
|
||||
except Exception:
|
||||
self.log.warning("GUI event loop or pylab initialization failed")
|
||||
self.shell.showtraceback()
|
||||
return
|
||||
|
||||
if isinstance(r, tuple):
|
||||
gui, backend = r[:2]
|
||||
self.log.info("Enabling GUI event loop integration, "
|
||||
"eventloop=%s, matplotlib=%s", gui, backend)
|
||||
if key == "auto":
|
||||
print("Using matplotlib backend: %s" % backend)
|
||||
else:
|
||||
gui = r
|
||||
self.log.info("Enabling GUI event loop integration, "
|
||||
"eventloop=%s", gui)
|
||||
|
||||
def init_extensions(self):
|
||||
"""Load all IPython extensions in IPythonApp.extensions.
|
||||
|
||||
This uses the :meth:`ExtensionManager.load_extensions` to load all
|
||||
the extensions listed in ``self.extensions``.
|
||||
"""
|
||||
try:
|
||||
self.log.debug("Loading IPython extensions...")
|
||||
extensions = self.default_extensions + self.extensions
|
||||
if self.extra_extension:
|
||||
extensions.append(self.extra_extension)
|
||||
for ext in extensions:
|
||||
try:
|
||||
self.log.info("Loading IPython extension: %s" % ext)
|
||||
self.shell.extension_manager.load_extension(ext)
|
||||
except:
|
||||
if self.reraise_ipython_extension_failures:
|
||||
raise
|
||||
msg = ("Error in loading extension: {ext}\n"
|
||||
"Check your config files in {location}".format(
|
||||
ext=ext,
|
||||
location=self.profile_dir.location
|
||||
))
|
||||
self.log.warning(msg, exc_info=True)
|
||||
except:
|
||||
if self.reraise_ipython_extension_failures:
|
||||
raise
|
||||
self.log.warning("Unknown error in loading extensions:", exc_info=True)
|
||||
|
||||
def init_code(self):
|
||||
"""run the pre-flight code, specified via exec_lines"""
|
||||
self._run_startup_files()
|
||||
self._run_exec_lines()
|
||||
self._run_exec_files()
|
||||
|
||||
# Hide variables defined here from %who etc.
|
||||
if self.hide_initial_ns:
|
||||
self.shell.user_ns_hidden.update(self.shell.user_ns)
|
||||
|
||||
# command-line execution (ipython -i script.py, ipython -m module)
|
||||
# should *not* be excluded from %whos
|
||||
self._run_cmd_line_code()
|
||||
self._run_module()
|
||||
|
||||
# flush output, so itwon't be attached to the first cell
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
|
||||
def _run_exec_lines(self):
|
||||
"""Run lines of code in IPythonApp.exec_lines in the user's namespace."""
|
||||
if not self.exec_lines:
|
||||
return
|
||||
try:
|
||||
self.log.debug("Running code from IPythonApp.exec_lines...")
|
||||
for line in self.exec_lines:
|
||||
try:
|
||||
self.log.info("Running code in user namespace: %s" %
|
||||
line)
|
||||
self.shell.run_cell(line, store_history=False)
|
||||
except:
|
||||
self.log.warning("Error in executing line in user "
|
||||
"namespace: %s" % line)
|
||||
self.shell.showtraceback()
|
||||
except:
|
||||
self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
|
||||
self.shell.showtraceback()
|
||||
|
||||
def _exec_file(self, fname, shell_futures=False):
|
||||
try:
|
||||
full_filename = filefind(fname, [u'.', self.ipython_dir])
|
||||
except IOError:
|
||||
self.log.warning("File not found: %r"%fname)
|
||||
return
|
||||
# Make sure that the running script gets a proper sys.argv as if it
|
||||
# were run from a system shell.
|
||||
save_argv = sys.argv
|
||||
sys.argv = [full_filename] + self.extra_args[1:]
|
||||
try:
|
||||
if os.path.isfile(full_filename):
|
||||
self.log.info("Running file in user namespace: %s" %
|
||||
full_filename)
|
||||
# Ensure that __file__ is always defined to match Python
|
||||
# behavior.
|
||||
with preserve_keys(self.shell.user_ns, '__file__'):
|
||||
self.shell.user_ns['__file__'] = fname
|
||||
if full_filename.endswith('.ipy'):
|
||||
self.shell.safe_execfile_ipy(full_filename,
|
||||
shell_futures=shell_futures)
|
||||
else:
|
||||
# default to python, even without extension
|
||||
self.shell.safe_execfile(full_filename,
|
||||
self.shell.user_ns,
|
||||
shell_futures=shell_futures,
|
||||
raise_exceptions=True)
|
||||
finally:
|
||||
sys.argv = save_argv
|
||||
|
||||
def _run_startup_files(self):
|
||||
"""Run files from profile startup directory"""
|
||||
startup_dirs = [self.profile_dir.startup_dir] + [
|
||||
os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)
|
||||
]
|
||||
startup_files = []
|
||||
|
||||
if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
|
||||
not (self.file_to_run or self.code_to_run or self.module_to_run):
|
||||
python_startup = os.environ['PYTHONSTARTUP']
|
||||
self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
|
||||
try:
|
||||
self._exec_file(python_startup)
|
||||
except:
|
||||
self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
|
||||
self.shell.showtraceback()
|
||||
for startup_dir in startup_dirs[::-1]:
|
||||
startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
|
||||
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
|
||||
if not startup_files:
|
||||
return
|
||||
|
||||
self.log.debug("Running startup files from %s...", startup_dir)
|
||||
try:
|
||||
for fname in sorted(startup_files):
|
||||
self._exec_file(fname)
|
||||
except:
|
||||
self.log.warning("Unknown error in handling startup files:")
|
||||
self.shell.showtraceback()
|
||||
|
||||
def _run_exec_files(self):
|
||||
"""Run files from IPythonApp.exec_files"""
|
||||
if not self.exec_files:
|
||||
return
|
||||
|
||||
self.log.debug("Running files in IPythonApp.exec_files...")
|
||||
try:
|
||||
for fname in self.exec_files:
|
||||
self._exec_file(fname)
|
||||
except:
|
||||
self.log.warning("Unknown error in handling IPythonApp.exec_files:")
|
||||
self.shell.showtraceback()
|
||||
|
||||
def _run_cmd_line_code(self):
|
||||
"""Run code or file specified at the command-line"""
|
||||
if self.code_to_run:
|
||||
line = self.code_to_run
|
||||
try:
|
||||
self.log.info("Running code given at command line (c=): %s" %
|
||||
line)
|
||||
self.shell.run_cell(line, store_history=False)
|
||||
except:
|
||||
self.log.warning("Error in executing line in user namespace: %s" %
|
||||
line)
|
||||
self.shell.showtraceback()
|
||||
if not self.interact:
|
||||
self.exit(1)
|
||||
|
||||
# Like Python itself, ignore the second if the first of these is present
|
||||
elif self.file_to_run:
|
||||
fname = self.file_to_run
|
||||
if os.path.isdir(fname):
|
||||
fname = os.path.join(fname, "__main__.py")
|
||||
try:
|
||||
self._exec_file(fname, shell_futures=True)
|
||||
except:
|
||||
self.shell.showtraceback(tb_offset=4)
|
||||
if not self.interact:
|
||||
self.exit(1)
|
||||
|
||||
def _run_module(self):
|
||||
"""Run module specified at the command-line."""
|
||||
if self.module_to_run:
|
||||
# Make sure that the module gets a proper sys.argv as if it were
|
||||
# run using `python -m`.
|
||||
save_argv = sys.argv
|
||||
sys.argv = [sys.executable] + self.extra_args
|
||||
try:
|
||||
self.shell.safe_run_module(self.module_to_run,
|
||||
self.shell.user_ns)
|
||||
finally:
|
||||
sys.argv = save_argv
|
83
packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap
Normal file
83
packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap
Normal file
@@ -0,0 +1,83 @@
|
||||
|
||||
:- use_module(library(yapi)).
|
||||
|
||||
:- use_module(library(python)).
|
||||
|
||||
:- python_import(sys).
|
||||
|
||||
jupyter_query(Self, Cell) :-
|
||||
setup_call_cleanup(
|
||||
enter_cell(Self),
|
||||
python_query(Self, Cell),
|
||||
exit_cell(Self)
|
||||
).
|
||||
|
||||
enter_cell(_Self) :-
|
||||
open('//python/sys.stdout', append, _Output, [alias(jupo)]),
|
||||
open('//python/sys.stdout', append, _, [alias(jupe)]),
|
||||
set_prolog_flag(user_output, jupo),
|
||||
set_prolog_flag(user_error, jupe).
|
||||
|
||||
exit_cell(_Self) :-
|
||||
close( jupo),
|
||||
close( jupe).
|
||||
|
||||
|
||||
completions(S, Self) :-
|
||||
open(atom(S), read, St),
|
||||
scan_to_list(St, Tokens),
|
||||
reverse(Tokens, RTokens),
|
||||
setof( Completion, complete(RTokens, Completion), Cs),
|
||||
Self.completions := Cs.
|
||||
|
||||
complete( [atom(F)|LibRest], C) :-
|
||||
LibRest = [l, atom(Where)|Consult],
|
||||
isconsult(Consult, Rest),
|
||||
\+ arg( Rest ),
|
||||
check_library( F, Where, C).
|
||||
complete( [atom(F)|Consult], C) :-
|
||||
isconsult(Consult, Rest),
|
||||
\+ arg( Rest ),
|
||||
check_file( F, C).
|
||||
complete( [atom(F)|Rest], C) :-
|
||||
\+ arg( Rest ),
|
||||
predicate( F, Pred, Arity ),
|
||||
cont( Arity, Pred, C).
|
||||
|
||||
isconsult( [l, use_module| _Rest]).
|
||||
isconsult( [l, ensure_loaded| _Rest]).
|
||||
isconsult( [l, compile| _Rest]).
|
||||
isconsult( [l, consult| _Rest]).
|
||||
isconsult( [l, reconsult| _Rest]).
|
||||
isconsult( [l, load_files| _Rest]).
|
||||
isconsult( ['-', ']'| _Rest]).
|
||||
isconsult( [']'| _Rest]).
|
||||
|
||||
arg(([']'|_]).
|
||||
arg(([l|_]).
|
||||
|
||||
check_file(F,C) :-
|
||||
atom_concat( F, '*' , Pat),
|
||||
absolute_file_name( Pat, C0, [glob(true)] ),
|
||||
atom_concat(['\'',C0,'\''], C).
|
||||
|
||||
check_library( Lib, F, C) :-
|
||||
atom_concat( F, '*' , Pat),
|
||||
LibF =.. [Lib(Pat)],
|
||||
absolute_file_name( LibF, Lib, [glob(true)] ),
|
||||
file_directory_name( Lib, Name),
|
||||
( atom_concat(C, '.yap', Name) -> true ;
|
||||
atom_concat(C, '.ypp', Name) -> true ;
|
||||
atom_concat(C, '.prolog', Name) -> true
|
||||
).
|
||||
|
||||
predicate(N,P,A) :-
|
||||
system_predicate(P0/A),
|
||||
atom_concat(N,P,P0).
|
||||
predicate(N,P,A) :-
|
||||
current_predicate(P0/A),
|
||||
atom_concat(N,P,P0).
|
||||
|
||||
cont(0, P, P).
|
||||
cont( _, P, PB ):-
|
||||
atom_concat( P, '(', PB ).
|
@@ -1,5 +1,16 @@
|
||||
import sys
|
||||
import trace
|
||||
|
||||
# create a Trace object, telling it what to ignore, and whether to
|
||||
# do tracing or line-counting or both.
|
||||
tracer = trace.Trace(
|
||||
# ignoredirs=[sys.prefix, sys.exec_prefix],
|
||||
trace=1,
|
||||
count=0)
|
||||
|
||||
if __name__ == '__main__':
|
||||
from yap_kernel import kernelapp as app
|
||||
# tracer.run('app.launch_new_instance()')
|
||||
app.launch_new_instance()
|
||||
|
||||
|
||||
|
@@ -5,6 +5,8 @@
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
from IPython.utils.py3compat import str_to_bytes
|
||||
|
||||
import json
|
||||
import sys
|
||||
from subprocess import Popen, PIPE
|
||||
@@ -13,7 +15,6 @@ import warnings
|
||||
from IPython.core.profiledir import ProfileDir
|
||||
from IPython.paths import get_ipython_dir
|
||||
from ipython_genutils.path import filefind
|
||||
from ipython_genutils.py3compat import str_to_bytes
|
||||
|
||||
import jupyter_client
|
||||
from jupyter_client import write_connection_file
|
||||
@@ -39,7 +40,7 @@ def get_connection_file(app=None):
|
||||
|
||||
def find_connection_file(filename='kernel-*.json', profile=None):
|
||||
"""DEPRECATED: find a connection file, and return its absolute path.
|
||||
|
||||
|
||||
THIS FUNCION IS DEPRECATED. Use juptyer_client.find_connection_file instead.
|
||||
|
||||
Parameters
|
||||
@@ -54,7 +55,7 @@ def find_connection_file(filename='kernel-*.json', profile=None):
|
||||
-------
|
||||
str : The absolute path of the connection file.
|
||||
"""
|
||||
|
||||
|
||||
import warnings
|
||||
warnings.warn("""yap_kernel.find_connection_file is deprecated, use jupyter_client.find_connection_file""",
|
||||
DeprecationWarning, stacklevel=2)
|
||||
@@ -77,13 +78,13 @@ def find_connection_file(filename='kernel-*.json', profile=None):
|
||||
# find profiledir by profile name:
|
||||
profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
|
||||
security_dir = profile_dir.security_dir
|
||||
|
||||
|
||||
return jupyter_client.find_connection_file(filename, path=['.', security_dir])
|
||||
|
||||
|
||||
def _find_connection_file(connection_file, profile=None):
|
||||
"""Return the absolute path for a connection file
|
||||
|
||||
|
||||
- If nothing specified, return current Kernel's connection file
|
||||
- If profile specified, show deprecation warning about finding connection files in profiles
|
||||
- Otherwise, call jupyter_client.find_connection_file
|
||||
|
941
packages/python/yap_kernel/yap_kernel/formatters.py
Normal file
941
packages/python/yap_kernel/yap_kernel/formatters.py
Normal file
@@ -0,0 +1,941 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Display formatters.
|
||||
|
||||
Inheritance diagram:
|
||||
|
||||
.. inheritance-diagram:: IPython.core.formatters
|
||||
:parts: 3
|
||||
"""
|
||||
|
||||
# Copyright (c) IPython Development Team.
|
||||
# Distributed under the terms of the Modified BSD License.
|
||||
|
||||
import abc
|
||||
import json
|
||||
import sys
|
||||
import traceback
|
||||
import warnings
|
||||
from io import StringIO
|
||||
|
||||
from IPython.lib import pretty
|
||||
from IPython.utils.dir2 import get_real_method
|
||||
from IPython.utils.sentinel import Sentinel
|
||||
from decorator import decorator
|
||||
from traitlets import (
|
||||
Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
|
||||
ForwardDeclaredInstance,
|
||||
default, observe,
|
||||
)
|
||||
from traitlets.config.configurable import Configurable
|
||||
|
||||
from packages.python.yap_kernel.core.yap_kernel.getipython import get_ipython
|
||||
|
||||
|
||||
class DisplayFormatter(Configurable):
|
||||
|
||||
active_types = List(Unicode(),
|
||||
help="""List of currently active mime-types to display.
|
||||
You can use this to set a white-list for formats to display.
|
||||
|
||||
Most users will not need to change this value.
|
||||
""").tag(config=True)
|
||||
|
||||
@default('active_types')
|
||||
def _active_types_default(self):
|
||||
return self.format_types
|
||||
|
||||
@observe('active_types')
|
||||
def _active_types_changed(self, change):
|
||||
for key, formatter in self.formatters.items():
|
||||
if key in change['new']:
|
||||
formatter.enabled = True
|
||||
else:
|
||||
formatter.enabled = False
|
||||
|
||||
ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
|
||||
@default('ipython_display_formatter')
|
||||
def _default_formatter(self):
|
||||
return IPythonDisplayFormatter(parent=self)
|
||||
|
||||
# A dict of formatter whose keys are format types (MIME types) and whose
|
||||
# values are subclasses of BaseFormatter.
|
||||
formatters = Dict()
|
||||
@default('formatters')
|
||||
def _formatters_default(self):
|
||||
"""Activate the default formatters."""
|
||||
formatter_classes = [
|
||||
PlainTextFormatter,
|
||||
HTMLFormatter,
|
||||
MarkdownFormatter,
|
||||
SVGFormatter,
|
||||
PNGFormatter,
|
||||
PDFFormatter,
|
||||
JPEGFormatter,
|
||||
LatexFormatter,
|
||||
JSONFormatter,
|
||||
JavascriptFormatter
|
||||
]
|
||||
d = {}
|
||||
for cls in formatter_classes:
|
||||
f = cls(parent=self)
|
||||
d[f.format_type] = f
|
||||
return d
|
||||
|
||||
def format(self, obj, include=None, exclude=None):
|
||||
"""Return a format data dict for an object.
|
||||
|
||||
By default all format types will be computed.
|
||||
|
||||
The following MIME types are currently implemented:
|
||||
|
||||
* text/plain
|
||||
* text/html
|
||||
* text/markdown
|
||||
* text/latex
|
||||
* application/json
|
||||
* application/javascript
|
||||
* application/pdf
|
||||
* image/png
|
||||
* image/jpeg
|
||||
* image/svg+xml
|
||||
|
||||
Parameters
|
||||
----------
|
||||
obj : object
|
||||
The Python object whose format data will be computed.
|
||||
include : list or tuple, optional
|
||||
A list of format type strings (MIME types) to include in the
|
||||
format data dict. If this is set *only* the format types included
|
||||
in this list will be computed.
|
||||
exclude : list or tuple, optional
|
||||
A list of format type string (MIME types) to exclude in the format
|
||||
data dict. If this is set all format types will be computed,
|
||||
except for those included in this argument.
|
||||
|
||||
Returns
|
||||
-------
|
||||
(format_dict, metadata_dict) : tuple of two dicts
|
||||
|
||||
format_dict is a dictionary of key/value pairs, one of each format that was
|
||||
generated for the object. The keys are the format types, which
|
||||
will usually be MIME type strings and the values and JSON'able
|
||||
data structure containing the raw data for the representation in
|
||||
that format.
|
||||
|
||||
metadata_dict is a dictionary of metadata about each mime-type output.
|
||||
Its keys will be a strict subset of the keys in format_dict.
|
||||
"""
|
||||
format_dict = {}
|
||||
md_dict = {}
|
||||
|
||||
if self.ipython_display_formatter(obj):
|
||||
# object handled itself, don't proceed
|
||||
return {}, {}
|
||||
|
||||
for format_type, formatter in self.formatters.items():
|
||||
if include and format_type not in include:
|
||||
continue
|
||||
if exclude and format_type in exclude:
|
||||
continue
|
||||
|
||||
md = None
|
||||
try:
|
||||
data = formatter(obj)
|
||||
except:
|
||||
# FIXME: log the exception
|
||||
raise
|
||||
|
||||
# formatters can return raw data or (data, metadata)
|
||||
if isinstance(data, tuple) and len(data) == 2:
|
||||
data, md = data
|
||||
|
||||
if data is not None:
|
||||
format_dict[format_type] = data
|
||||
if md is not None:
|
||||
md_dict[format_type] = md
|
||||
|
||||
return format_dict, md_dict
|
||||
|
||||
@property
|
||||
def format_types(self):
|
||||
"""Return the format types (MIME types) of the active formatters."""
|
||||
return list(self.formatters.keys())
|
||||
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Formatters for specific format types (text, html, svg, etc.)
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _safe_repr(obj):
|
||||
"""Try to return a repr of an object
|
||||
|
||||
always returns a string, at least.
|
||||
"""
|
||||
try:
|
||||
return repr(obj)
|
||||
except Exception as e:
|
||||
return "un-repr-able object (%r)" % e
|
||||
|
||||
|
||||
class FormatterWarning(UserWarning):
|
||||
"""Warning class for errors in formatters"""
|
||||
|
||||
@decorator
|
||||
def catch_format_error(method, self, *args, **kwargs):
|
||||
"""show traceback on failed format call"""
|
||||
try:
|
||||
r = method(self, *args, **kwargs)
|
||||
except NotImplementedError:
|
||||
# don't warn on NotImplementedErrors
|
||||
return None
|
||||
except Exception:
|
||||
exc_info = sys.exc_info()
|
||||
ip = get_ipython()
|
||||
if ip is not None:
|
||||
ip.showtraceback(exc_info)
|
||||
else:
|
||||
traceback.print_exception(*exc_info)
|
||||
return None
|
||||
return self._check_return(r, args[0])
|
||||
|
||||
|
||||
class FormatterABC(metaclass=abc.ABCMeta):
|
||||
""" Abstract base class for Formatters.
|
||||
|
||||
A formatter is a callable class that is responsible for computing the
|
||||
raw format data for a particular format type (MIME type). For example,
|
||||
an HTML formatter would have a format type of `text/html` and would return
|
||||
the HTML representation of the object when called.
|
||||
"""
|
||||
|
||||
# The format type of the data returned, usually a MIME type.
|
||||
format_type = 'text/plain'
|
||||
|
||||
# Is the formatter enabled...
|
||||
enabled = True
|
||||
|
||||
@abc.abstractmethod
|
||||
def __call__(self, obj):
|
||||
"""Return a JSON'able representation of the object.
|
||||
|
||||
If the object cannot be formatted by this formatter,
|
||||
warn and return None.
|
||||
"""
|
||||
return repr(obj)
|
||||
|
||||
|
||||
def _mod_name_key(typ):
|
||||
"""Return a (__module__, __name__) tuple for a type.
|
||||
|
||||
Used as key in Formatter.deferred_printers.
|
||||
"""
|
||||
module = getattr(typ, '__module__', None)
|
||||
name = getattr(typ, '__name__', None)
|
||||
return (module, name)
|
||||
|
||||
|
||||
def _get_type(obj):
|
||||
"""Return the type of an instance (old and new-style)"""
|
||||
return getattr(obj, '__class__', None) or type(obj)
|
||||
|
||||
|
||||
_raise_key_error = Sentinel('_raise_key_error', __name__,
|
||||
"""
|
||||
Special value to raise a KeyError
|
||||
|
||||
Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
|
||||
""")
|
||||
|
||||
|
||||
class BaseFormatter(Configurable):
|
||||
"""A base formatter class that is configurable.
|
||||
|
||||
This formatter should usually be used as the base class of all formatters.
|
||||
It is a traited :class:`Configurable` class and includes an extensible
|
||||
API for users to determine how their objects are formatted. The following
|
||||
logic is used to find a function to format an given object.
|
||||
|
||||
1. The object is introspected to see if it has a method with the name
|
||||
:attr:`print_method`. If is does, that object is passed to that method
|
||||
for formatting.
|
||||
2. If no print method is found, three internal dictionaries are consulted
|
||||
to find print method: :attr:`singleton_printers`, :attr:`type_printers`
|
||||
and :attr:`deferred_printers`.
|
||||
|
||||
Users should use these dictionaries to register functions that will be
|
||||
used to compute the format data for their objects (if those objects don't
|
||||
have the special print methods). The easiest way of using these
|
||||
dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
|
||||
methods.
|
||||
|
||||
If no function/callable is found to compute the format data, ``None`` is
|
||||
returned and this format type is not used.
|
||||
"""
|
||||
|
||||
format_type = Unicode('text/plain')
|
||||
_return_type = str
|
||||
|
||||
enabled = Bool(True).tag(config=True)
|
||||
|
||||
print_method = ObjectName('__repr__')
|
||||
|
||||
# The singleton printers.
|
||||
# Maps the IDs of the builtin singleton objects to the format functions.
|
||||
singleton_printers = Dict().tag(config=True)
|
||||
|
||||
# The type-specific printers.
|
||||
# Map type objects to the format functions.
|
||||
type_printers = Dict().tag(config=True)
|
||||
|
||||
# The deferred-import type-specific printers.
|
||||
# Map (modulename, classname) pairs to the format functions.
|
||||
deferred_printers = Dict().tag(config=True)
|
||||
|
||||
@catch_format_error
|
||||
def __call__(self, obj):
|
||||
"""Compute the format for an object."""
|
||||
if self.enabled:
|
||||
# lookup registered printer
|
||||
try:
|
||||
printer = self.lookup(obj)
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
return printer(obj)
|
||||
# Finally look for special method names
|
||||
method = get_real_method(obj, self.print_method)
|
||||
if method is not None:
|
||||
return method()
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
|
||||
def __contains__(self, typ):
|
||||
"""map in to lookup_by_type"""
|
||||
try:
|
||||
self.lookup_by_type(typ)
|
||||
except KeyError:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def _check_return(self, r, obj):
|
||||
"""Check that a return value is appropriate
|
||||
|
||||
Return the value if so, None otherwise, warning if invalid.
|
||||
"""
|
||||
if r is None or isinstance(r, self._return_type) or \
|
||||
(isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
|
||||
return r
|
||||
else:
|
||||
warnings.warn(
|
||||
"%s formatter returned invalid type %s (expected %s) for object: %s" % \
|
||||
(self.format_type, type(r), self._return_type, _safe_repr(obj)),
|
||||
FormatterWarning
|
||||
)
|
||||
|
||||
def lookup(self, obj):
|
||||
"""Look up the formatter for a given instance.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
obj : object instance
|
||||
|
||||
Returns
|
||||
-------
|
||||
f : callable
|
||||
The registered formatting callable for the type.
|
||||
|
||||
Raises
|
||||
------
|
||||
KeyError if the type has not been registered.
|
||||
"""
|
||||
# look for singleton first
|
||||
obj_id = id(obj)
|
||||
if obj_id in self.singleton_printers:
|
||||
return self.singleton_printers[obj_id]
|
||||
# then lookup by type
|
||||
return self.lookup_by_type(_get_type(obj))
|
||||
|
||||
def lookup_by_type(self, typ):
|
||||
"""Look up the registered formatter for a type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
typ : type or '__module__.__name__' string for a type
|
||||
|
||||
Returns
|
||||
-------
|
||||
f : callable
|
||||
The registered formatting callable for the type.
|
||||
|
||||
Raises
|
||||
------
|
||||
KeyError if the type has not been registered.
|
||||
"""
|
||||
if isinstance(typ, str):
|
||||
typ_key = tuple(typ.rsplit('.',1))
|
||||
if typ_key not in self.deferred_printers:
|
||||
# We may have it cached in the type map. We will have to
|
||||
# iterate over all of the types to check.
|
||||
for cls in self.type_printers:
|
||||
if _mod_name_key(cls) == typ_key:
|
||||
return self.type_printers[cls]
|
||||
else:
|
||||
return self.deferred_printers[typ_key]
|
||||
else:
|
||||
for cls in pretty._get_mro(typ):
|
||||
if cls in self.type_printers or self._in_deferred_types(cls):
|
||||
return self.type_printers[cls]
|
||||
|
||||
# If we have reached here, the lookup failed.
|
||||
raise KeyError("No registered printer for {0!r}".format(typ))
|
||||
|
||||
def for_type(self, typ, func=None):
|
||||
"""Add a format function for a given type.
|
||||
|
||||
Parameters
|
||||
-----------
|
||||
typ : type or '__module__.__name__' string for a type
|
||||
The class of the object that will be formatted using `func`.
|
||||
func : callable
|
||||
A callable for computing the format data.
|
||||
`func` will be called with the object to be formatted,
|
||||
and will return the raw data in this formatter's format.
|
||||
Subclasses may use a different call signature for the
|
||||
`func` argument.
|
||||
|
||||
If `func` is None or not specified, there will be no change,
|
||||
only returning the current value.
|
||||
|
||||
Returns
|
||||
-------
|
||||
oldfunc : callable
|
||||
The currently registered callable.
|
||||
If you are registering a new formatter,
|
||||
this will be the previous value (to enable restoring later).
|
||||
"""
|
||||
# if string given, interpret as 'pkg.module.class_name'
|
||||
if isinstance(typ, str):
|
||||
type_module, type_name = typ.rsplit('.', 1)
|
||||
return self.for_type_by_name(type_module, type_name, func)
|
||||
|
||||
try:
|
||||
oldfunc = self.lookup_by_type(typ)
|
||||
except KeyError:
|
||||
oldfunc = None
|
||||
|
||||
if func is not None:
|
||||
self.type_printers[typ] = func
|
||||
|
||||
return oldfunc
|
||||
|
||||
def for_type_by_name(self, type_module, type_name, func=None):
|
||||
"""Add a format function for a type specified by the full dotted
|
||||
module and name of the type, rather than the type of the object.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
type_module : str
|
||||
The full dotted name of the module the type is defined in, like
|
||||
``numpy``.
|
||||
type_name : str
|
||||
The name of the type (the class name), like ``dtype``
|
||||
func : callable
|
||||
A callable for computing the format data.
|
||||
`func` will be called with the object to be formatted,
|
||||
and will return the raw data in this formatter's format.
|
||||
Subclasses may use a different call signature for the
|
||||
`func` argument.
|
||||
|
||||
If `func` is None or unspecified, there will be no change,
|
||||
only returning the current value.
|
||||
|
||||
Returns
|
||||
-------
|
||||
oldfunc : callable
|
||||
The currently registered callable.
|
||||
If you are registering a new formatter,
|
||||
this will be the previous value (to enable restoring later).
|
||||
"""
|
||||
key = (type_module, type_name)
|
||||
|
||||
try:
|
||||
oldfunc = self.lookup_by_type("%s.%s" % key)
|
||||
except KeyError:
|
||||
oldfunc = None
|
||||
|
||||
if func is not None:
|
||||
self.deferred_printers[key] = func
|
||||
return oldfunc
|
||||
|
||||
def pop(self, typ, default=_raise_key_error):
|
||||
"""Pop a formatter for the given type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
typ : type or '__module__.__name__' string for a type
|
||||
default : object
|
||||
value to be returned if no formatter is registered for typ.
|
||||
|
||||
Returns
|
||||
-------
|
||||
obj : object
|
||||
The last registered object for the type.
|
||||
|
||||
Raises
|
||||
------
|
||||
KeyError if the type is not registered and default is not specified.
|
||||
"""
|
||||
|
||||
if isinstance(typ, str):
|
||||
typ_key = tuple(typ.rsplit('.',1))
|
||||
if typ_key not in self.deferred_printers:
|
||||
# We may have it cached in the type map. We will have to
|
||||
# iterate over all of the types to check.
|
||||
for cls in self.type_printers:
|
||||
if _mod_name_key(cls) == typ_key:
|
||||
old = self.type_printers.pop(cls)
|
||||
break
|
||||
else:
|
||||
old = default
|
||||
else:
|
||||
old = self.deferred_printers.pop(typ_key)
|
||||
else:
|
||||
if typ in self.type_printers:
|
||||
old = self.type_printers.pop(typ)
|
||||
else:
|
||||
old = self.deferred_printers.pop(_mod_name_key(typ), default)
|
||||
if old is _raise_key_error:
|
||||
raise KeyError("No registered value for {0!r}".format(typ))
|
||||
return old
|
||||
|
||||
def _in_deferred_types(self, cls):
|
||||
"""
|
||||
Check if the given class is specified in the deferred type registry.
|
||||
|
||||
Successful matches will be moved to the regular type registry for future use.
|
||||
"""
|
||||
mod = getattr(cls, '__module__', None)
|
||||
name = getattr(cls, '__name__', None)
|
||||
key = (mod, name)
|
||||
if key in self.deferred_printers:
|
||||
# Move the printer over to the regular registry.
|
||||
printer = self.deferred_printers.pop(key)
|
||||
self.type_printers[cls] = printer
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class PlainTextFormatter(BaseFormatter):
|
||||
"""The default pretty-printer.
|
||||
|
||||
This uses :mod:`IPython.lib.pretty` to compute the format data of
|
||||
the object. If the object cannot be pretty printed, :func:`repr` is used.
|
||||
See the documentation of :mod:`IPython.lib.pretty` for details on
|
||||
how to write pretty printers. Here is a simple example::
|
||||
|
||||
def dtype_pprinter(obj, p, cycle):
|
||||
if cycle:
|
||||
return p.text('dtype(...)')
|
||||
if hasattr(obj, 'fields'):
|
||||
if obj.fields is None:
|
||||
p.text(repr(obj))
|
||||
else:
|
||||
p.begin_group(7, 'dtype([')
|
||||
for i, field in enumerate(obj.descr):
|
||||
if i > 0:
|
||||
p.text(',')
|
||||
p.breakable()
|
||||
p.pretty(field)
|
||||
p.end_group(7, '])')
|
||||
"""
|
||||
|
||||
# The format type of data returned.
|
||||
format_type = Unicode('text/plain')
|
||||
|
||||
# This subclass ignores this attribute as it always need to return
|
||||
# something.
|
||||
enabled = Bool(True).tag(config=False)
|
||||
|
||||
max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
|
||||
help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
|
||||
|
||||
Set to 0 to disable truncation.
|
||||
"""
|
||||
).tag(config=True)
|
||||
|
||||
# Look for a _repr_pretty_ methods to use for pretty printing.
|
||||
print_method = ObjectName('_repr_pretty_')
|
||||
|
||||
# Whether to pretty-print or not.
|
||||
pprint = Bool(True).tag(config=True)
|
||||
|
||||
# Whether to be verbose or not.
|
||||
verbose = Bool(False).tag(config=True)
|
||||
|
||||
# The maximum width.
|
||||
max_width = Integer(79).tag(config=True)
|
||||
|
||||
# The newline character.
|
||||
newline = Unicode('\n').tag(config=True)
|
||||
|
||||
# format-string for pprinting floats
|
||||
float_format = Unicode('%r')
|
||||
# setter for float precision, either int or direct format-string
|
||||
float_precision = CUnicode('').tag(config=True)
|
||||
|
||||
@observe('float_precision')
|
||||
def _float_precision_changed(self, change):
|
||||
"""float_precision changed, set float_format accordingly.
|
||||
|
||||
float_precision can be set by int or str.
|
||||
This will set float_format, after interpreting input.
|
||||
If numpy has been imported, numpy print precision will also be set.
|
||||
|
||||
integer `n` sets format to '%.nf', otherwise, format set directly.
|
||||
|
||||
An empty string returns to defaults (repr for float, 8 for numpy).
|
||||
|
||||
This parameter can be set via the '%precision' magic.
|
||||
"""
|
||||
|
||||
new = change['new']
|
||||
if '%' in new:
|
||||
# got explicit format string
|
||||
fmt = new
|
||||
try:
|
||||
fmt%3.14159
|
||||
except Exception:
|
||||
raise ValueError("Precision must be int or format string, not %r"%new)
|
||||
elif new:
|
||||
# otherwise, should be an int
|
||||
try:
|
||||
i = int(new)
|
||||
assert i >= 0
|
||||
except ValueError:
|
||||
raise ValueError("Precision must be int or format string, not %r"%new)
|
||||
except AssertionError:
|
||||
raise ValueError("int precision must be non-negative, not %r"%i)
|
||||
|
||||
fmt = '%%.%if'%i
|
||||
if 'numpy' in sys.modules:
|
||||
# set numpy precision if it has been imported
|
||||
import numpy
|
||||
numpy.set_printoptions(precision=i)
|
||||
else:
|
||||
# default back to repr
|
||||
fmt = '%r'
|
||||
if 'numpy' in sys.modules:
|
||||
import numpy
|
||||
# numpy default is 8
|
||||
numpy.set_printoptions(precision=8)
|
||||
self.float_format = fmt
|
||||
|
||||
# Use the default pretty printers from IPython.lib.pretty.
|
||||
@default('singleton_printers')
|
||||
def _singleton_printers_default(self):
|
||||
return pretty._singleton_pprinters.copy()
|
||||
|
||||
@default('type_printers')
|
||||
def _type_printers_default(self):
|
||||
d = pretty._type_pprinters.copy()
|
||||
d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
|
||||
return d
|
||||
|
||||
@default('deferred_printers')
|
||||
def _deferred_printers_default(self):
|
||||
return pretty._deferred_type_pprinters.copy()
|
||||
|
||||
#### FormatterABC interface ####
|
||||
|
||||
@catch_format_error
|
||||
def __call__(self, obj):
|
||||
"""Compute the pretty representation of the object."""
|
||||
if not self.pprint:
|
||||
return repr(obj)
|
||||
else:
|
||||
stream = StringIO()
|
||||
printer = pretty.RepresentationPrinter(stream, self.verbose,
|
||||
self.max_width, self.newline,
|
||||
max_seq_length=self.max_seq_length,
|
||||
singleton_pprinters=self.singleton_printers,
|
||||
type_pprinters=self.type_printers,
|
||||
deferred_pprinters=self.deferred_printers)
|
||||
printer.pretty(obj)
|
||||
printer.flush()
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
class HTMLFormatter(BaseFormatter):
|
||||
"""An HTML formatter.
|
||||
|
||||
To define the callables that compute the HTML representation of your
|
||||
objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be a valid HTML snippet that
|
||||
could be injected into an existing DOM. It should *not* include the
|
||||
```<html>`` or ```<body>`` tags.
|
||||
"""
|
||||
format_type = Unicode('text/html')
|
||||
|
||||
print_method = ObjectName('_repr_html_')
|
||||
|
||||
|
||||
class MarkdownFormatter(BaseFormatter):
|
||||
"""A Markdown formatter.
|
||||
|
||||
To define the callables that compute the Markdown representation of your
|
||||
objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be a valid Markdown.
|
||||
"""
|
||||
format_type = Unicode('text/markdown')
|
||||
|
||||
print_method = ObjectName('_repr_markdown_')
|
||||
|
||||
class SVGFormatter(BaseFormatter):
|
||||
"""An SVG formatter.
|
||||
|
||||
To define the callables that compute the SVG representation of your
|
||||
objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be valid SVG enclosed in
|
||||
```<svg>``` tags, that could be injected into an existing DOM. It should
|
||||
*not* include the ```<html>`` or ```<body>`` tags.
|
||||
"""
|
||||
format_type = Unicode('image/svg+xml')
|
||||
|
||||
print_method = ObjectName('_repr_svg_')
|
||||
|
||||
|
||||
class PNGFormatter(BaseFormatter):
|
||||
"""A PNG formatter.
|
||||
|
||||
To define the callables that compute the PNG representation of your
|
||||
objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be raw PNG data, *not*
|
||||
base64 encoded.
|
||||
"""
|
||||
format_type = Unicode('image/png')
|
||||
|
||||
print_method = ObjectName('_repr_png_')
|
||||
|
||||
_return_type = (bytes, str)
|
||||
|
||||
|
||||
class JPEGFormatter(BaseFormatter):
|
||||
"""A JPEG formatter.
|
||||
|
||||
To define the callables that compute the JPEG representation of your
|
||||
objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be raw JPEG data, *not*
|
||||
base64 encoded.
|
||||
"""
|
||||
format_type = Unicode('image/jpeg')
|
||||
|
||||
print_method = ObjectName('_repr_jpeg_')
|
||||
|
||||
_return_type = (bytes, str)
|
||||
|
||||
|
||||
class LatexFormatter(BaseFormatter):
|
||||
"""A LaTeX formatter.
|
||||
|
||||
To define the callables that compute the LaTeX representation of your
|
||||
objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be a valid LaTeX equation,
|
||||
enclosed in either ```$```, ```$$``` or another LaTeX equation
|
||||
environment.
|
||||
"""
|
||||
format_type = Unicode('text/latex')
|
||||
|
||||
print_method = ObjectName('_repr_latex_')
|
||||
|
||||
|
||||
class JSONFormatter(BaseFormatter):
|
||||
"""A JSON string formatter.
|
||||
|
||||
To define the callables that compute the JSONable representation of
|
||||
your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be a JSONable list or dict.
|
||||
JSON scalars (None, number, string) are not allowed, only dict or list containers.
|
||||
"""
|
||||
format_type = Unicode('application/json')
|
||||
_return_type = (list, dict)
|
||||
|
||||
print_method = ObjectName('_repr_json_')
|
||||
|
||||
def _check_return(self, r, obj):
|
||||
"""Check that a return value is appropriate
|
||||
|
||||
Return the value if so, None otherwise, warning if invalid.
|
||||
"""
|
||||
if r is None:
|
||||
return
|
||||
md = None
|
||||
if isinstance(r, tuple):
|
||||
# unpack data, metadata tuple for type checking on first element
|
||||
r, md = r
|
||||
|
||||
# handle deprecated JSON-as-string form from IPython < 3
|
||||
if isinstance(r, str):
|
||||
warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
|
||||
FormatterWarning)
|
||||
r = json.loads(r)
|
||||
|
||||
if md is not None:
|
||||
# put the tuple back together
|
||||
r = (r, md)
|
||||
return super(JSONFormatter, self)._check_return(r, obj)
|
||||
|
||||
|
||||
class JavascriptFormatter(BaseFormatter):
|
||||
"""A Javascript formatter.
|
||||
|
||||
To define the callables that compute the Javascript representation of
|
||||
your objects, define a :meth:`_repr_javascript_` method or use the
|
||||
:meth:`for_type` or :meth:`for_type_by_name` methods to register functions
|
||||
that handle this.
|
||||
|
||||
The return value of this formatter should be valid Javascript code and
|
||||
should *not* be enclosed in ```<script>``` tags.
|
||||
"""
|
||||
format_type = Unicode('application/javascript')
|
||||
|
||||
print_method = ObjectName('_repr_javascript_')
|
||||
|
||||
|
||||
class PDFFormatter(BaseFormatter):
|
||||
"""A PDF formatter.
|
||||
|
||||
To define the callables that compute the PDF representation of your
|
||||
objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this.
|
||||
|
||||
The return value of this formatter should be raw PDF data, *not*
|
||||
base64 encoded.
|
||||
"""
|
||||
format_type = Unicode('application/pdf')
|
||||
|
||||
print_method = ObjectName('_repr_pdf_')
|
||||
|
||||
_return_type = (bytes, str)
|
||||
|
||||
class IPythonDisplayFormatter(BaseFormatter):
|
||||
"""A Formatter for objects that know how to display themselves.
|
||||
|
||||
To define the callables that compute the representation of your
|
||||
objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
|
||||
or :meth:`for_type_by_name` methods to register functions that handle
|
||||
this. Unlike mime-type displays, this method should not return anything,
|
||||
instead calling any appropriate display methods itself.
|
||||
|
||||
This display formatter has highest priority.
|
||||
If it fires, no other display formatter will be called.
|
||||
"""
|
||||
print_method = ObjectName('_ipython_display_')
|
||||
_return_type = (type(None), bool)
|
||||
|
||||
|
||||
@catch_format_error
|
||||
def __call__(self, obj):
|
||||
"""Compute the format for an object."""
|
||||
if self.enabled:
|
||||
# lookup registered printer
|
||||
try:
|
||||
printer = self.lookup(obj)
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
printer(obj)
|
||||
return True
|
||||
# Finally look for special method names
|
||||
method = get_real_method(obj, self.print_method)
|
||||
if method is not None:
|
||||
method()
|
||||
return True
|
||||
|
||||
|
||||
FormatterABC.register(BaseFormatter)
|
||||
FormatterABC.register(PlainTextFormatter)
|
||||
FormatterABC.register(HTMLFormatter)
|
||||
FormatterABC.register(MarkdownFormatter)
|
||||
FormatterABC.register(SVGFormatter)
|
||||
FormatterABC.register(PNGFormatter)
|
||||
FormatterABC.register(PDFFormatter)
|
||||
FormatterABC.register(JPEGFormatter)
|
||||
FormatterABC.register(LatexFormatter)
|
||||
FormatterABC.register(JSONFormatter)
|
||||
FormatterABC.register(JavascriptFormatter)
|
||||
FormatterABC.register(IPythonDisplayFormatter)
|
||||
|
||||
|
||||
def format_display_data(obj, include=None, exclude=None):
|
||||
"""Return a format data dict for an object.
|
||||
|
||||
By default all format types will be computed.
|
||||
|
||||
The following MIME types are currently implemented:
|
||||
|
||||
* text/plain
|
||||
* text/html
|
||||
* text/markdown
|
||||
* text/latex
|
||||
* application/json
|
||||
* application/javascript
|
||||
* application/pdf
|
||||
* image/png
|
||||
* image/jpeg
|
||||
* image/svg+xml
|
||||
|
||||
Parameters
|
||||
----------
|
||||
obj : object
|
||||
The Python object whose format data will be computed.
|
||||
|
||||
Returns
|
||||
-------
|
||||
format_dict : dict
|
||||
A dictionary of key/value pairs, one or each format that was
|
||||
generated for the object. The keys are the format types, which
|
||||
will usually be MIME type strings and the values and JSON'able
|
||||
data structure containing the raw data for the representation in
|
||||
that format.
|
||||
include : list or tuple, optional
|
||||
A list of format type strings (MIME types) to include in the
|
||||
format data dict. If this is set *only* the format types included
|
||||
in this list will be computed.
|
||||
exclude : list or tuple, optional
|
||||
A list of format type string (MIME types) to exclue in the format
|
||||
data dict. If this is set all format types will be computed,
|
||||
except for those included in this argument.
|
||||
"""
|
||||
from yap_ipython.core.interactiveshell import InteractiveShell
|
||||
|
||||
return InteractiveShell.instance().display_formatter.format(
|
||||
obj,
|
||||
include,
|
||||
exclude
|
||||
)
|
||||
|
525
packages/python/yap_kernel/yap_kernel/inputtransformer.py
Normal file
525
packages/python/yap_kernel/yap_kernel/inputtransformer.py
Normal file
@@ -0,0 +1,525 @@
|
||||
"""Input transformer classes to support IPython special syntax.
|
||||
|
||||
This includes the machinery to recognise and transform ``%magic`` commands,
|
||||
``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
|
||||
"""
|
||||
import abc
|
||||
import functools
|
||||
import re
|
||||
from io import StringIO
|
||||
|
||||
from IPython.core.splitinput import LineInfo
|
||||
from IPython.utils import tokenize2
|
||||
from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Globals
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
# The escape sequences that define the syntax transformations IPython will
|
||||
# apply to user input. These can NOT be just changed here: many regular
|
||||
# expressions and other parts of the code may use their hardcoded values, and
|
||||
# for all intents and purposes they constitute the 'IPython syntax', so they
|
||||
# should be considered fixed.
|
||||
|
||||
ESC_SHELL = '!' # Send line to underlying system shell
|
||||
ESC_SH_CAP = '!!' # Send line to system shell and capture output
|
||||
ESC_HELP = '?' # Find information about object
|
||||
ESC_HELP2 = '??' # Find extra-detailed information about object
|
||||
ESC_MAGIC = '%' # Call magic function
|
||||
ESC_MAGIC2 = '%%' # Call cell-magic function
|
||||
ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
|
||||
ESC_QUOTE2 = ';' # Quote all args as a single string, call
|
||||
ESC_PAREN = '/' # Call first argument with rest of line as arguments
|
||||
|
||||
ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
|
||||
ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
|
||||
ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
|
||||
|
||||
|
||||
class InputTransformer(metaclass=abc.ABCMeta):
|
||||
"""Abstract base class for line-based input transformers."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def push(self, line):
|
||||
"""Send a line of input to the transformer, returning the transformed
|
||||
input or None if the transformer is waiting for more input.
|
||||
|
||||
Must be overridden by subclasses.
|
||||
|
||||
Implementations may raise ``SyntaxError`` if the input is invalid. No
|
||||
other exceptions may be raised.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def reset(self):
|
||||
"""Return, transformed any lines that the transformer has accumulated,
|
||||
and reset its internal state.
|
||||
|
||||
Must be overridden by subclasses.
|
||||
"""
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def wrap(cls, func):
|
||||
"""Can be used by subclasses as a decorator, to return a factory that
|
||||
will allow instantiation with the decorated object.
|
||||
"""
|
||||
@functools.wraps(func)
|
||||
def transformer_factory(**kwargs):
|
||||
return cls(func, **kwargs)
|
||||
|
||||
return transformer_factory
|
||||
|
||||
class StatelessInputTransformer(InputTransformer):
|
||||
"""Wrapper for a stateless input transformer implemented as a function."""
|
||||
def __init__(self, func):
|
||||
self.func = func
|
||||
|
||||
def __repr__(self):
|
||||
return "StatelessInputTransformer(func={0!r})".format(self.func)
|
||||
|
||||
def push(self, line):
|
||||
"""Send a line of input to the transformer, returning the
|
||||
transformed input."""
|
||||
return self.func(line)
|
||||
|
||||
def reset(self):
|
||||
"""No-op - exists for compatibility."""
|
||||
pass
|
||||
|
||||
class CoroutineInputTransformer(InputTransformer):
|
||||
"""Wrapper for an input transformer implemented as a coroutine."""
|
||||
def __init__(self, coro, **kwargs):
|
||||
# Prime it
|
||||
self.coro = coro(**kwargs)
|
||||
next(self.coro)
|
||||
|
||||
def __repr__(self):
|
||||
return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
|
||||
|
||||
def push(self, line):
|
||||
"""Send a line of input to the transformer, returning the
|
||||
transformed input or None if the transformer is waiting for more
|
||||
input.
|
||||
"""
|
||||
return self.coro.send(line)
|
||||
|
||||
def reset(self):
|
||||
"""Return, transformed any lines that the transformer has
|
||||
accumulated, and reset its internal state.
|
||||
"""
|
||||
return self.coro.send(None)
|
||||
|
||||
class TokenInputTransformer(InputTransformer):
|
||||
"""Wrapper for a token-based input transformer.
|
||||
|
||||
func should accept a list of tokens (5-tuples, see tokenize docs), and
|
||||
return an iterable which can be passed to tokenize.untokenize().
|
||||
"""
|
||||
def __init__(self, func):
|
||||
self.func = func
|
||||
self.buf = []
|
||||
self.reset_tokenizer()
|
||||
|
||||
def reset_tokenizer(self):
|
||||
it = iter(self.buf)
|
||||
self.tokenizer = generate_tokens(it.__next__)
|
||||
|
||||
def push(self, line):
|
||||
self.buf.append(line + '\n')
|
||||
if all(l.isspace() for l in self.buf):
|
||||
return self.reset()
|
||||
|
||||
tokens = []
|
||||
stop_at_NL = False
|
||||
try:
|
||||
for intok in self.tokenizer:
|
||||
tokens.append(intok)
|
||||
t = intok[0]
|
||||
if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
|
||||
# Stop before we try to pull a line we don't have yet
|
||||
break
|
||||
elif t == tokenize2.ERRORTOKEN:
|
||||
stop_at_NL = True
|
||||
except TokenError:
|
||||
# Multi-line statement - stop and try again with the next line
|
||||
self.reset_tokenizer()
|
||||
return None
|
||||
|
||||
return self.output(tokens)
|
||||
|
||||
def output(self, tokens):
|
||||
self.buf.clear()
|
||||
self.reset_tokenizer()
|
||||
return untokenize(self.func(tokens)).rstrip('\n')
|
||||
|
||||
def reset(self):
|
||||
l = ''.join(self.buf)
|
||||
self.buf.clear()
|
||||
self.reset_tokenizer()
|
||||
if l:
|
||||
return l.rstrip('\n')
|
||||
|
||||
class assemble_python_lines(TokenInputTransformer):
|
||||
def __init__(self):
|
||||
super(assemble_python_lines, self).__init__(None)
|
||||
|
||||
def output(self, tokens):
|
||||
return self.reset()
|
||||
|
||||
@CoroutineInputTransformer.wrap
|
||||
def assemble_logical_lines():
|
||||
"""Join lines following explicit line continuations (\)"""
|
||||
line = ''
|
||||
while True:
|
||||
line = (yield line)
|
||||
if not line or line.isspace():
|
||||
continue
|
||||
|
||||
parts = []
|
||||
while line is not None:
|
||||
if line.endswith('\\') and (not has_comment(line)):
|
||||
parts.append(line[:-1])
|
||||
line = (yield None) # Get another line
|
||||
else:
|
||||
parts.append(line)
|
||||
break
|
||||
|
||||
# Output
|
||||
line = ''.join(parts)
|
||||
|
||||
# Utilities
|
||||
def _make_help_call(target, esc, lspace, next_input=None):
|
||||
"""Prepares a pinfo(2)/psearch call from a target name and the escape
|
||||
(i.e. ? or ??)"""
|
||||
method = 'pinfo2' if esc == '??' \
|
||||
else 'psearch' if '*' in target \
|
||||
else 'pinfo'
|
||||
arg = " ".join([method, target])
|
||||
if next_input is None:
|
||||
return '%sget_ipython().magic(%r)' % (lspace, arg)
|
||||
else:
|
||||
return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
|
||||
(lspace, next_input, arg)
|
||||
|
||||
# These define the transformations for the different escape characters.
|
||||
def _tr_system(line_info):
|
||||
"Translate lines escaped with: !"
|
||||
cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
|
||||
return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
|
||||
|
||||
def _tr_system2(line_info):
|
||||
"Translate lines escaped with: !!"
|
||||
cmd = line_info.line.lstrip()[2:]
|
||||
return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
|
||||
|
||||
def _tr_help(line_info):
|
||||
"Translate lines escaped with: ?/??"
|
||||
# A naked help line should just fire the intro help screen
|
||||
if not line_info.line[1:]:
|
||||
return 'get_ipython().show_usage()'
|
||||
|
||||
return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
|
||||
|
||||
def _tr_magic(line_info):
|
||||
"Translate lines escaped with: %"
|
||||
tpl = '%sget_ipython().magic(%r)'
|
||||
if line_info.line.startswith(ESC_MAGIC2):
|
||||
return line_info.line
|
||||
cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
|
||||
return tpl % (line_info.pre, cmd)
|
||||
|
||||
def _tr_quote(line_info):
|
||||
"Translate lines escaped with: ,"
|
||||
return '%s%s("%s")' % (line_info.pre, line_info.ifun,
|
||||
'", "'.join(line_info.the_rest.split()) )
|
||||
|
||||
def _tr_quote2(line_info):
|
||||
"Translate lines escaped with: ;"
|
||||
return '%s%s("%s")' % (line_info.pre, line_info.ifun,
|
||||
line_info.the_rest)
|
||||
|
||||
def _tr_paren(line_info):
|
||||
"Translate lines escaped with: /"
|
||||
return '%s%s(%s)' % (line_info.pre, line_info.ifun,
|
||||
", ".join(line_info.the_rest.split()))
|
||||
|
||||
tr = { ESC_SHELL : _tr_system,
|
||||
ESC_SH_CAP : _tr_system2,
|
||||
ESC_HELP : _tr_help,
|
||||
ESC_HELP2 : _tr_help,
|
||||
ESC_MAGIC : _tr_magic,
|
||||
ESC_QUOTE : _tr_quote,
|
||||
ESC_QUOTE2 : _tr_quote2,
|
||||
ESC_PAREN : _tr_paren }
|
||||
|
||||
@StatelessInputTransformer.wrap
|
||||
def escaped_commands(line):
|
||||
"""Transform escaped commands - %magic, !system, ?help + various autocalls.
|
||||
"""
|
||||
if not line or line.isspace():
|
||||
return line
|
||||
lineinf = LineInfo(line)
|
||||
if lineinf.esc not in tr:
|
||||
return line
|
||||
|
||||
return tr[lineinf.esc](lineinf)
|
||||
|
||||
_initial_space_re = re.compile(r'\s*')
|
||||
|
||||
_help_end_re = re.compile(r"""(%{0,2}
|
||||
[a-zA-Z_*][\w*]* # Variable name
|
||||
(\.[a-zA-Z_*][\w*]*)* # .etc.etc
|
||||
)
|
||||
(\?\??)$ # ? or ??
|
||||
""",
|
||||
re.VERBOSE)
|
||||
|
||||
# Extra pseudotokens for multiline strings and data structures
|
||||
_MULTILINE_STRING = object()
|
||||
_MULTILINE_STRUCTURE = object()
|
||||
|
||||
def _line_tokens(line):
|
||||
"""Helper for has_comment and ends_in_comment_or_string."""
|
||||
readline = StringIO(line).readline
|
||||
toktypes = set()
|
||||
try:
|
||||
for t in generate_tokens(readline):
|
||||
toktypes.add(t[0])
|
||||
except TokenError as e:
|
||||
# There are only two cases where a TokenError is raised.
|
||||
if 'multi-line string' in e.args[0]:
|
||||
toktypes.add(_MULTILINE_STRING)
|
||||
else:
|
||||
toktypes.add(_MULTILINE_STRUCTURE)
|
||||
return toktypes
|
||||
|
||||
def has_comment(src):
|
||||
"""Indicate whether an input line has (i.e. ends in, or is) a comment.
|
||||
|
||||
This uses tokenize, so it can distinguish comments from # inside strings.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
src : string
|
||||
A single line input string.
|
||||
|
||||
Returns
|
||||
-------
|
||||
comment : bool
|
||||
True if source has a comment.
|
||||
"""
|
||||
return (tokenize2.COMMENT in _line_tokens(src))
|
||||
|
||||
def ends_in_comment_or_string(src):
|
||||
"""Indicates whether or not an input line ends in a comment or within
|
||||
a multiline string.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
src : string
|
||||
A single line input string.
|
||||
|
||||
Returns
|
||||
-------
|
||||
comment : bool
|
||||
True if source ends in a comment or multiline string.
|
||||
"""
|
||||
toktypes = _line_tokens(src)
|
||||
return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
|
||||
|
||||
|
||||
@StatelessInputTransformer.wrap
|
||||
def help_end(line):
|
||||
"""Translate lines with ?/?? at the end"""
|
||||
m = _help_end_re.search(line)
|
||||
if m is None or ends_in_comment_or_string(line):
|
||||
return line
|
||||
target = m.group(1)
|
||||
esc = m.group(3)
|
||||
lspace = _initial_space_re.match(line).group(0)
|
||||
|
||||
# If we're mid-command, put it back on the next prompt for the user.
|
||||
next_input = line.rstrip('?') if line.strip() != m.group(0) else None
|
||||
|
||||
return _make_help_call(target, esc, lspace, next_input)
|
||||
|
||||
|
||||
@CoroutineInputTransformer.wrap
|
||||
def cellmagic(end_on_blank_line=False):
|
||||
"""Captures & transforms cell magics.
|
||||
|
||||
After a cell magic is started, this stores up any lines it gets until it is
|
||||
reset (sent None).
|
||||
"""
|
||||
tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
|
||||
cellmagic_help_re = re.compile('%%\w+\?')
|
||||
line = ''
|
||||
while True:
|
||||
line = (yield line)
|
||||
# consume leading empty lines
|
||||
while not line:
|
||||
line = (yield line)
|
||||
|
||||
if not line.startswith(ESC_MAGIC2):
|
||||
# This isn't a cell magic, idle waiting for reset then start over
|
||||
while line is not None:
|
||||
line = (yield line)
|
||||
continue
|
||||
|
||||
if cellmagic_help_re.match(line):
|
||||
# This case will be handled by help_end
|
||||
continue
|
||||
|
||||
first = line
|
||||
body = []
|
||||
line = (yield None)
|
||||
while (line is not None) and \
|
||||
((line.strip() != '') or not end_on_blank_line):
|
||||
body.append(line)
|
||||
line = (yield None)
|
||||
|
||||
# Output
|
||||
magic_name, _, first = first.partition(' ')
|
||||
magic_name = magic_name.lstrip(ESC_MAGIC2)
|
||||
line = tpl % (magic_name, first, u'\n'.join(body))
|
||||
|
||||
|
||||
def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None):
|
||||
"""Remove matching input prompts from a block of input.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
prompt_re : regular expression
|
||||
A regular expression matching any input prompt (including continuation)
|
||||
initial_re : regular expression, optional
|
||||
A regular expression matching only the initial prompt, but not continuation.
|
||||
If no initial expression is given, prompt_re will be used everywhere.
|
||||
Used mainly for plain Python prompts, where the continuation prompt
|
||||
``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
|
||||
|
||||
If initial_re and prompt_re differ,
|
||||
only initial_re will be tested against the first line.
|
||||
If any prompt is found on the first two lines,
|
||||
prompts will be stripped from the rest of the block.
|
||||
"""
|
||||
if initial_re is None:
|
||||
initial_re = prompt_re
|
||||
line = ''
|
||||
while True:
|
||||
line = (yield line)
|
||||
|
||||
# First line of cell
|
||||
if line is None:
|
||||
continue
|
||||
out, n1 = initial_re.subn('', line, count=1)
|
||||
if turnoff_re and not n1:
|
||||
if turnoff_re.match(line):
|
||||
# We're in e.g. a cell magic; disable this transformer for
|
||||
# the rest of the cell.
|
||||
while line is not None:
|
||||
line = (yield line)
|
||||
continue
|
||||
|
||||
line = (yield out)
|
||||
|
||||
if line is None:
|
||||
continue
|
||||
# check for any prompt on the second line of the cell,
|
||||
# because people often copy from just after the first prompt,
|
||||
# so we might not see it in the first line.
|
||||
out, n2 = prompt_re.subn('', line, count=1)
|
||||
line = (yield out)
|
||||
|
||||
if n1 or n2:
|
||||
# Found a prompt in the first two lines - check for it in
|
||||
# the rest of the cell as well.
|
||||
while line is not None:
|
||||
line = (yield prompt_re.sub('', line, count=1))
|
||||
|
||||
else:
|
||||
# Prompts not in input - wait for reset
|
||||
while line is not None:
|
||||
line = (yield line)
|
||||
|
||||
@CoroutineInputTransformer.wrap
|
||||
def classic_prompt():
|
||||
"""Strip the >>>/... prompts of the Python interactive shell."""
|
||||
# FIXME: non-capturing version (?:...) usable?
|
||||
prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)')
|
||||
initial_re = re.compile(r'^>>>( |$)')
|
||||
# Any %magic/!system is IPython syntax, so we needn't look for >>> prompts
|
||||
turnoff_re = re.compile(r'^[%!]')
|
||||
return _strip_prompts(prompt_re, initial_re, turnoff_re)
|
||||
|
||||
@CoroutineInputTransformer.wrap
|
||||
def ipy_prompt():
|
||||
"""Strip IPython's In [1]:/...: prompts."""
|
||||
# FIXME: non-capturing version (?:...) usable?
|
||||
prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)')
|
||||
# Disable prompt stripping inside cell magics
|
||||
turnoff_re = re.compile(r'^%%')
|
||||
return _strip_prompts(prompt_re, turnoff_re=turnoff_re)
|
||||
|
||||
|
||||
@CoroutineInputTransformer.wrap
|
||||
def leading_indent():
|
||||
"""Remove leading indentation.
|
||||
|
||||
If the first line starts with a spaces or tabs, the same whitespace will be
|
||||
removed from each following line until it is reset.
|
||||
"""
|
||||
space_re = re.compile(r'^[ \t]+')
|
||||
line = ''
|
||||
while True:
|
||||
line = (yield line)
|
||||
|
||||
if line is None:
|
||||
continue
|
||||
|
||||
m = space_re.match(line)
|
||||
if m:
|
||||
space = m.group(0)
|
||||
while line is not None:
|
||||
if line.startswith(space):
|
||||
line = line[len(space):]
|
||||
line = (yield line)
|
||||
else:
|
||||
# No leading spaces - wait for reset
|
||||
while line is not None:
|
||||
line = (yield line)
|
||||
|
||||
|
||||
_assign_pat = \
|
||||
r'''(?P<lhs>(\s*)
|
||||
([\w\.]+) # Initial identifier
|
||||
(\s*,\s*
|
||||
\*?[\w\.]+)* # Further identifiers for unpacking
|
||||
\s*?,? # Trailing comma
|
||||
)
|
||||
\s*=\s*
|
||||
'''
|
||||
|
||||
assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
|
||||
assign_system_template = '%s = get_ipython().getoutput(%r)'
|
||||
@StatelessInputTransformer.wrap
|
||||
def assign_from_system(line):
|
||||
"""Transform assignment from system commands (e.g. files = !ls)"""
|
||||
m = assign_system_re.match(line)
|
||||
if m is None:
|
||||
return line
|
||||
|
||||
return assign_system_template % m.group('lhs', 'cmd')
|
||||
|
||||
assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
|
||||
assign_magic_template = '%s = get_ipython().magic(%r)'
|
||||
@StatelessInputTransformer.wrap
|
||||
def assign_from_magic(line):
|
||||
"""Transform assignment from magic commands (e.g. a = %who_ls)"""
|
||||
m = assign_magic_re.match(line)
|
||||
if m is None:
|
||||
return line
|
||||
|
||||
return assign_magic_template % m.group('lhs', 'cmd')
|
@@ -21,8 +21,8 @@ from IPython.core.application import (
|
||||
BaseIPythonApplication, base_flags, base_aliases, catch_config_error
|
||||
)
|
||||
from IPython.core.profiledir import ProfileDir
|
||||
from IPython.core.shellapp import (
|
||||
InteractiveShellApp, shell_flags, shell_aliases
|
||||
from yap_ipython.core.shellapp import (
|
||||
YAPInteractiveApp, shell_flags, shell_aliases
|
||||
)
|
||||
from IPython.utils import io
|
||||
from ipython_genutils.path import filefind, ensure_dir_exists
|
||||
@@ -96,7 +96,7 @@ To read more about this, see https://github.com/ipython/ipython/issues/2049
|
||||
# Application class for starting an IPython Kernel
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
class YAPKernelApp(BaseIPythonApplication, InteractiveShellApp,
|
||||
class YAPKernelApp(BaseIPythonApplication, YAPInteractiveApp,
|
||||
ConnectionFileMixin):
|
||||
name='YAP Kernel'
|
||||
aliases = Dict(kernel_aliases)
|
||||
@@ -385,7 +385,7 @@ class YAPKernelApp(BaseIPythonApplication, InteractiveShellApp,
|
||||
if not os.environ.get('MPLBACKEND'):
|
||||
os.environ['MPLBACKEND'] = 'module://yap_kernel.pylab.backend_inline'
|
||||
|
||||
# Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
|
||||
# Provide a wrapper for :meth:`YAPInteractiveApp.init_gui_pylab`
|
||||
# to ensure that any exception is printed straight to stderr.
|
||||
# Normally _showtraceback associates the reply with an execution,
|
||||
# which means frontends will never draw it, as this exception
|
||||
@@ -400,7 +400,7 @@ class YAPKernelApp(BaseIPythonApplication, InteractiveShellApp,
|
||||
file=sys.stderr)
|
||||
print (shell.InteractiveTB.stb2text(stb), file=sys.stderr)
|
||||
shell._showtraceback = print_tb
|
||||
InteractiveShellApp.init_gui_pylab(self)
|
||||
YAPInteractiveApp.init_gui_pylab(self)
|
||||
finally:
|
||||
shell._showtraceback = _showtraceback
|
||||
|
||||
|
@@ -16,7 +16,7 @@ from jupyter_client.kernelspec import KernelSpecManager
|
||||
|
||||
pjoin = os.path.join
|
||||
|
||||
KERNEL_NAME = 'YAPKernel'
|
||||
KERNEL_NAME = 'yap_kernel'
|
||||
|
||||
# path to kernelspec resources
|
||||
RESOURCES = pjoin(os.path.dirname(__file__), 'resources')
|
||||
@@ -59,7 +59,7 @@ def get_kernel_dict(extra_arguments=None):
|
||||
}
|
||||
|
||||
|
||||
def write_kernel_spec(path=None, overrides=None, extra_arguments=None):
|
||||
def write_kernel_spec(path=os.path.join(tempfile.mkdtemp(suffix='_kernels'), KERNEL_NAME), overrides=None, extra_arguments=None):
|
||||
"""Write a kernel spec directory to `path`
|
||||
|
||||
If `path` is not specified, a temporary directory is created.
|
||||
@@ -69,7 +69,7 @@ def write_kernel_spec(path=None, overrides=None, extra_arguments=None):
|
||||
"""
|
||||
if path is None:
|
||||
path = os.path.join(tempfile.mkdtemp(suffix='_kernels'), KERNEL_NAME)
|
||||
|
||||
print( path )
|
||||
# stage resources
|
||||
shutil.copytree(RESOURCES, path)
|
||||
# write kernel.json
|
||||
@@ -142,7 +142,7 @@ from traitlets.config import Application
|
||||
|
||||
class InstallYAPKernelSpecApp(Application):
|
||||
"""Dummy app wrapping argparse"""
|
||||
name = 'ipython-kernel-install'
|
||||
name = 'yap-kernel-install'
|
||||
|
||||
def initialize(self, argv=None):
|
||||
if argv is None:
|
||||
@@ -152,12 +152,12 @@ class InstallYAPKernelSpecApp(Application):
|
||||
def start(self):
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(prog=self.name,
|
||||
description="Install the IPython kernel spec.")
|
||||
description="Install the YAP kernel spec.")
|
||||
parser.add_argument('--user', action='store_true',
|
||||
help="Install for the current user instead of system-wide")
|
||||
parser.add_argument('--name', type=str, default=KERNEL_NAME,
|
||||
help="Specify a name for the kernelspec."
|
||||
" This is needed to have multiple IPython kernels at the same time.")
|
||||
" This is needed to have multiple YAP kernels at the same time.")
|
||||
parser.add_argument('--display-name', type=str,
|
||||
help="Specify the display name for the kernelspec."
|
||||
" This is helpful when you have multiple IPython kernels.")
|
||||
|
@@ -1,28 +0,0 @@
|
||||
|
||||
|
||||
:- use_module(library(python)).
|
||||
|
||||
:- initialization
|
||||
ensure_loaded(library(yapi) ),
|
||||
python_import(sys).
|
||||
|
||||
%% @pred yap_query(0:Goalc, - Dictionary)
|
||||
%%
|
||||
%% dictionary, Examples
|
||||
%%
|
||||
%%
|
||||
jupyter_query( Self, String ) :-
|
||||
set_python_output( Self, Output , Error),
|
||||
python_query( Self, String ),
|
||||
close( Output ),
|
||||
cloe( Error ).
|
||||
|
||||
|
||||
|
||||
set_python_output(_Self,Output,Error) :-
|
||||
open('//python/sys.stdout', append, Output, [alias(output)]),
|
||||
open('//python/sys.stderr', append, Error, [alias(error)]),
|
||||
yap_flag(user_output, output),
|
||||
yap_flag(user_error, error).
|
||||
|
||||
|
@@ -2,20 +2,19 @@
|
||||
|
||||
import getpass
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from IPython.core import release
|
||||
from ipython_genutils.py3compat import builtin_mod, PY3, unicode_type, safe_unicode
|
||||
from IPython.utils.tokenutil import token_at_cursor, line_at_cursor
|
||||
from ipython_genutils.py3compat import builtin_mod, PY3, unicode_type, safe_unicode
|
||||
from traitlets import Instance, Type, Any, List
|
||||
|
||||
from yap_ipython.core.interactiveshell import YAPInteractive
|
||||
from .comm import CommManager
|
||||
from .kernelbase import Kernel as KernelBase
|
||||
from .zmqshell import ZMQInteractiveShell
|
||||
from .interactiveshell import YAPInteraction
|
||||
|
||||
|
||||
class YAPKernel(KernelBase):
|
||||
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
|
||||
shell = Instance('yap_ipython.core.interactiveshell.YAPInteractiveABC',
|
||||
allow_none=True)
|
||||
shell_class = Type(ZMQInteractiveShell)
|
||||
user_module = Any()
|
||||
@@ -57,7 +56,7 @@ class YAPKernel(KernelBase):
|
||||
for msg_type in comm_msg_types:
|
||||
self.shell_handlers[msg_type] = getattr(self.comm_manager, msg_type)
|
||||
|
||||
self.engine = YAPInteraction(self)
|
||||
self.engine = YAPInteractive()
|
||||
self.shell._last_traceback = None
|
||||
self.shell.run_cell = self.engine.run_cell
|
||||
|
||||
@@ -100,8 +99,8 @@ class YAPKernel(KernelBase):
|
||||
'version': '6.3',
|
||||
'mimetype': 'text/x-prolog',
|
||||
'codemirror_mode': {
|
||||
'name': 'prolog',
|
||||
'version': sys.version_info[0]
|
||||
'name': 'prolog' #,
|
||||
#'version': '3'
|
||||
},
|
||||
'pygments_lexer': 'prolog',
|
||||
'nbconvert_exporter': 'prolog',
|
||||
|
@@ -25,8 +25,8 @@ from threading import local
|
||||
|
||||
from tornado import ioloop
|
||||
|
||||
from IPython.core.interactiveshell import (
|
||||
InteractiveShell, InteractiveShellABC
|
||||
from yap_ipython.core.interactiveshell import (
|
||||
YAPInteractive, YAPInteractiveABC
|
||||
)
|
||||
from IPython.core import page
|
||||
from IPython.core.autocall import ZMQExitAutocall
|
||||
@@ -437,7 +437,7 @@ class KernelMagics(Magics):
|
||||
print("Autosave disabled")
|
||||
|
||||
|
||||
class ZMQInteractiveShell(InteractiveShell):
|
||||
class ZMQInteractiveShell(YAPInteractive):
|
||||
"""A subclass of InteractiveShell for ZMQ."""
|
||||
|
||||
displayhook_class = Type(ZMQShellDisplayHook)
|
||||
@@ -598,4 +598,4 @@ class ZMQInteractiveShell(InteractiveShell):
|
||||
# https://ipython.readthedocs.io/en/latest/install/kernel_install.html
|
||||
pass
|
||||
|
||||
InteractiveShellABC.register(ZMQInteractiveShell)
|
||||
YAPInteractiveABC.register(ZMQInteractiveShell)
|
||||
|
@@ -12,5 +12,5 @@ if __name__ == '__main__':
|
||||
if sys.path[0] == '':
|
||||
del sys.path[0]
|
||||
|
||||
from inprocess.ipkernel import kernelapp as app
|
||||
from yap_kernel import kernelapp as app
|
||||
app.launch_new_instance()
|
||||
|
Reference in New Issue
Block a user