update Python
This commit is contained in:
parent
ff3185b551
commit
06f5fa2614
@ -2,7 +2,10 @@
|
|||||||
#CHECK: PythonLibs
|
#CHECK: PythonLibs
|
||||||
|
|
||||||
set (PYTHON_SOURCES
|
set (PYTHON_SOURCES
|
||||||
python.c)
|
python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c )
|
||||||
|
|
||||||
|
set (PYTHON_HEADERS
|
||||||
|
python.h)
|
||||||
|
|
||||||
#try to use Brew first
|
#try to use Brew first
|
||||||
#set ( PYTHON_LIBRARY /Anaconda/lib/libpython2.7.dylib )
|
#set ( PYTHON_LIBRARY /Anaconda/lib/libpython2.7.dylib )
|
||||||
@ -39,8 +42,15 @@ if (PYTHONLIBS_FOUND) # PYTHONLIBS_FOUND - have the Python l
|
|||||||
|
|
||||||
add_library (libpython SHARED ${PYTHON_SOURCES})
|
add_library (libpython SHARED ${PYTHON_SOURCES})
|
||||||
|
|
||||||
|
configure_file ("setup.py.cmake" "setup.py" )
|
||||||
|
|
||||||
target_link_libraries(libpython libYap ${PYTHON_LIBRARIES})
|
target_link_libraries(libpython libYap ${PYTHON_LIBRARIES})
|
||||||
|
|
||||||
|
set(SETUP_PY "${CMAKE_CURRENT_BINARY_DIR}/setup.py")
|
||||||
|
|
||||||
|
add_custom_target ( YAPex ALL
|
||||||
|
COMMAND ${PYTHON_EXECUTABLE} setup.py build -f
|
||||||
|
DEPENDS yapex.py )
|
||||||
|
|
||||||
set_target_properties (libpython PROPERTIES PREFIX "")
|
set_target_properties (libpython PROPERTIES PREFIX "")
|
||||||
|
|
||||||
@ -55,5 +65,7 @@ if (PYTHONLIBS_FOUND) # PYTHONLIBS_FOUND - have the Python l
|
|||||||
DESTINATION ${libpl}
|
DESTINATION ${libpl}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} install -f
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
|
||||||
|
|
||||||
endif (PYTHONLIBS_FOUND)
|
endif (PYTHONLIBS_FOUND)
|
||||||
|
@ -372,7 +372,6 @@ python_lhs((Exp1,Exp2), O) :- !,
|
|||||||
python_lhs(F, F).
|
python_lhs(F, F).
|
||||||
|
|
||||||
start_python :-
|
start_python :-
|
||||||
init_python,
|
|
||||||
python_main_module(MRef),
|
python_main_module(MRef),
|
||||||
assert(python_mref_cache('__main__', MRef)),
|
assert(python_mref_cache('__main__', MRef)),
|
||||||
python_command('import sys'),
|
python_command('import sys'),
|
||||||
@ -426,6 +425,5 @@ python_assign_field(C1.E, Obj) :-
|
|||||||
python_eval_term(C1, O1),
|
python_eval_term(C1, O1),
|
||||||
python_assign_field(O1, E, Obj ).
|
python_assign_field(O1, E, Obj ).
|
||||||
|
|
||||||
:- initialization( use_foreign_library(foreign(libpython)), now ).
|
:- initialization( use_foreign_library(foreign(libpython), init_python), now ).
|
||||||
|
|
||||||
:- initialization(start_python ).
|
|
||||||
|
@ -11,7 +11,7 @@ kernel_json = {
|
|||||||
"argv": [sys.executable,
|
"argv": [sys.executable,
|
||||||
"-m", "yap_kernel",
|
"-m", "yap_kernel",
|
||||||
"-f", "{connection_file}"],
|
"-f", "{connection_file}"],
|
||||||
"display_name": "MetaKernel YAP %i" % (3 if PY3 else 2),
|
"display_name": " YAP-6.3" ,
|
||||||
"language": "prolog",
|
"language": "prolog",
|
||||||
"name": "yap_kernel",
|
"name": "yap_kernel",
|
||||||
}
|
}
|
||||||
@ -19,7 +19,7 @@ kernel_json = {
|
|||||||
class install_with_kernelspec(install):
|
class install_with_kernelspec(install):
|
||||||
def run(self):
|
def run(self):
|
||||||
install.run(self)
|
install.run(self)
|
||||||
from IPython.kernel.kernelspec import install_kernel_spec
|
from jupyter_client.kernelspec import install_kernel_spec
|
||||||
from IPython.utils.tempdir import TemporaryDirectory
|
from IPython.utils.tempdir import TemporaryDirectory
|
||||||
with TemporaryDirectory() as td:
|
with TemporaryDirectory() as td:
|
||||||
os.chmod(td, 0o755) # Starts off as 700, not user readable
|
os.chmod(td, 0o755) # Starts off as 700, not user readable
|
||||||
@ -51,8 +51,8 @@ setup(name='yap_kernel',
|
|||||||
classifiers = [
|
classifiers = [
|
||||||
'Framework :: IPython',
|
'Framework :: IPython',
|
||||||
'License :: OSI Approved :: BSD License',
|
'License :: OSI Approved :: BSD License',
|
||||||
|
'Programming Language :: YAP :: 6.3',
|
||||||
'Programming Language :: Python :: 3',
|
'Programming Language :: Python :: 3',
|
||||||
'Programming Language :: Python :: 2',
|
|
||||||
'Topic :: System :: Shells',
|
'Topic :: System :: Shells',
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
@ -2,8 +2,17 @@ from __future__ import print_function
|
|||||||
|
|
||||||
from metakernel import MetaKernel
|
from metakernel import MetaKernel
|
||||||
|
|
||||||
|
import sys
|
||||||
import signal
|
import signal
|
||||||
import yap
|
import yap
|
||||||
|
import yapex
|
||||||
|
|
||||||
|
import ipywidgets as widgets
|
||||||
|
|
||||||
|
|
||||||
|
def eprint(*args, **kwargs):
|
||||||
|
print(*args, file=sys.stderr, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
class MetaKernelyap(MetaKernel):
|
class MetaKernelyap(MetaKernel):
|
||||||
implementation = 'MetaKernel YAP'
|
implementation = 'MetaKernel YAP'
|
||||||
@ -12,7 +21,7 @@ class MetaKernelyap(MetaKernel):
|
|||||||
language_version = '0.1'
|
language_version = '0.1'
|
||||||
banner = "MetaKernel YAP"
|
banner = "MetaKernel YAP"
|
||||||
language_info = {
|
language_info = {
|
||||||
'mimetype': 'text/plain',
|
'mimetype': 'text/prolog',
|
||||||
'name': 'text',
|
'name': 'text',
|
||||||
# ------ If different from 'language':
|
# ------ If different from 'language':
|
||||||
'codemirror_mode': {
|
'codemirror_mode': {
|
||||||
@ -26,24 +35,25 @@ class MetaKernelyap(MetaKernel):
|
|||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
|
|
||||||
MetaKernel.__init__(self, **kwargs)
|
MetaKernel.__init__(self, **kwargs)
|
||||||
self._start_yap()
|
self._start_yap(**kwargs)
|
||||||
|
self.olines = ""
|
||||||
|
self.ask = True
|
||||||
|
|
||||||
def _start_yap(self):
|
def _start_yap(self, **kwargs):
|
||||||
# Signal handlers are inherited by forked processes, and we can't easily
|
# Signal handlers are inherited by forked processes, and we can't easily
|
||||||
# reset it from the subprocess. Since kernelapp ignores SIGINT except in
|
# reset it from the subprocess. Since kernelapp ignores SIGINT except in
|
||||||
# message handlers, we need to temporarily reset the SIGINT handler here
|
# message handlers, we need to temporarily reset the SIGINT handler here
|
||||||
# so that yap and its children are interruptible.
|
# so that yap and its children are interruptible.
|
||||||
#sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
|
sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
|
||||||
#try:
|
try:
|
||||||
self.engine = yap.YAPEngine()
|
self.engine = yap.YAPEngine()
|
||||||
self.q = None
|
self.q = None
|
||||||
#engine.query("load_files(library(python), [])").command()
|
self.engine.query("load_files(library(python), [])").command()
|
||||||
banner = "YAP {0} Kernel".format(self.engine.version())
|
banner = "YAP {0} Kernel".format(self.engine.version())
|
||||||
|
self.olines = banner
|
||||||
#finally:
|
finally:
|
||||||
# signal.signal(signal.SIGINT, sig)
|
signal.signal(signal.SIGINT, sig)
|
||||||
|
|
||||||
# Register Yap function to write image data to temporary file
|
# Register Yap function to write image data to temporary file
|
||||||
#self.yapwrapper.run_command(image_setup_cmd)
|
#self.yapwrapper.run_command(image_setup_cmd)
|
||||||
@ -51,27 +61,141 @@ class MetaKernelyap(MetaKernel):
|
|||||||
def get_usage(self):
|
def get_usage(self):
|
||||||
return "This is the YAP kernel."
|
return "This is the YAP kernel."
|
||||||
|
|
||||||
|
def query_prolog(self, s):
|
||||||
|
|
||||||
|
if not self.q:
|
||||||
|
self.q = self.engine.query(s)
|
||||||
|
if self.q.next():
|
||||||
|
vs = self.q.namedVarsCopy()
|
||||||
|
wrote = False
|
||||||
|
if vs:
|
||||||
|
i = 0
|
||||||
|
for eq in vs:
|
||||||
|
name = eq[0]
|
||||||
|
bind = eq[1]
|
||||||
|
if bind.isVar():
|
||||||
|
var = yap.YAPAtom('$VAR')
|
||||||
|
f = yap.YAPFunctor(var, 1)
|
||||||
|
bind.unify(yap.YAPApplTerm(f, (name)))
|
||||||
|
else:
|
||||||
|
i = bind.numberVars(i, True)
|
||||||
|
print(name.text() + " = " + bind.text())
|
||||||
|
wrote = True
|
||||||
|
print("yes")
|
||||||
|
if self.q.deterministic():
|
||||||
|
self.closeq()
|
||||||
|
return
|
||||||
|
print("No (more) answers")
|
||||||
|
self.closeq()
|
||||||
|
return
|
||||||
|
|
||||||
|
def closeq( self):
|
||||||
|
if self.q:
|
||||||
|
self.q.close()
|
||||||
|
self.q = None
|
||||||
|
|
||||||
def do_execute_direct(self, code):
|
def do_execute_direct(self, code):
|
||||||
if not code.strip():
|
if not code.strip():
|
||||||
return ""
|
return ""
|
||||||
|
lines = code.split("\n")
|
||||||
interrupted = False
|
interrupted = False
|
||||||
|
self.doReset = True
|
||||||
|
nlines = ""
|
||||||
try:
|
try:
|
||||||
if self.q is None:
|
for line in lines:
|
||||||
self.q = self.engine.query(code.rstrip())
|
line = line.strip()
|
||||||
if self.q.next():
|
if line.startswith('#'):
|
||||||
vs = self.q.namedVars()
|
# wait
|
||||||
if vs:
|
print( "comment")
|
||||||
l = {}
|
elif line.startswith('%'):
|
||||||
for eq in vs:
|
# wait
|
||||||
l[eq.getArg(1)] = eq.getArg(2)
|
call_magic( line )
|
||||||
return l
|
elif line.endswith(';'):
|
||||||
|
nlines += line.rstrip(';').rstrip()
|
||||||
|
self.doReset = False
|
||||||
|
break
|
||||||
|
elif line.endswith('!'):
|
||||||
|
nlines += line.rstrip('!').rstrip()
|
||||||
|
self.ask = False
|
||||||
|
self.doReset = False
|
||||||
|
break
|
||||||
else:
|
else:
|
||||||
return 'yes'
|
line = line.rstrip()
|
||||||
|
if line:
|
||||||
|
nlines += line + "\n"
|
||||||
|
if nlines != self.olines:
|
||||||
|
self.closeq( )
|
||||||
|
self.olines = nlines
|
||||||
|
elif self.doReset:
|
||||||
|
opt = widgets.ToggleButtons(
|
||||||
|
description='Query Solutions:',
|
||||||
|
options=['First', 'Next', 'All'],
|
||||||
|
)
|
||||||
|
print( opt )
|
||||||
|
if opt == 'First':
|
||||||
|
self.closeq( )
|
||||||
|
elif opt == 'Next':
|
||||||
|
self.doReset = False
|
||||||
else:
|
else:
|
||||||
return 'no'
|
self.ask = False
|
||||||
|
self.doReset = False
|
||||||
|
self.query_prolog( nlines )
|
||||||
|
while not self.ask and self.q:
|
||||||
|
self.query_prolog( nlines )
|
||||||
|
|
||||||
|
except SyntaxError as err:
|
||||||
|
print("Syntax Error error: {0}".format(err))
|
||||||
|
except EOFError:
|
||||||
|
return
|
||||||
|
except RuntimeError as err:
|
||||||
|
print("YAP Execution Error: {0}".format(err))
|
||||||
|
except ValueError:
|
||||||
|
print("Could not convert data to an integer.")
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
return 'stopped by user'
|
return 'stopped by user'
|
||||||
|
except:
|
||||||
|
print("Unexpected error:", sys.exc_info()[0])
|
||||||
|
raise
|
||||||
|
|
||||||
|
def do_complete(self, code, cursor_pos):
|
||||||
|
eprint( code, " -- ", str(cursor_pos) )
|
||||||
|
# code = code[:cursor_pos]
|
||||||
|
# default = {'matches': [], 'cursor_start': 0,
|
||||||
|
# 'cursor_end': cursor_pos, 'metadata': dict(),
|
||||||
|
# 'status': 'ok'}
|
||||||
|
|
||||||
|
# if not code or code[-1] == ' ':
|
||||||
|
# return default
|
||||||
|
|
||||||
|
# tokens = code.replace(';', ' ').split()
|
||||||
|
# if not tokens:
|
||||||
|
# return default
|
||||||
|
|
||||||
|
# matches = []
|
||||||
|
# token = tokens[-1]
|
||||||
|
# start = cursor_pos - len(token)
|
||||||
|
|
||||||
|
# if token[0] == '$':
|
||||||
|
# # complete variables
|
||||||
|
# cmd = 'compgen -A arrayvar -A export -A variable %s' % token[1:] # strip leading $
|
||||||
|
# output = self.bashwrapper.run_command(cmd).rstrip()
|
||||||
|
# completions = set(output.split())
|
||||||
|
# # append matches including leading $
|
||||||
|
# matches.extend(['$'+c for c in completions])
|
||||||
|
# else:
|
||||||
|
# # complete functions and builtins
|
||||||
|
# cmd = 'compgen -cdfa %s' % token
|
||||||
|
# output = self.bashwrapper.run_command(cmd).rstrip()
|
||||||
|
# matches.extend(output.split())
|
||||||
|
|
||||||
|
# if not matches:
|
||||||
|
# return default
|
||||||
|
# matches = [m for m in matches if m.startswith(token)]
|
||||||
|
|
||||||
|
# return {'matches': sorted(matches), 'cursor_start': start,
|
||||||
|
# 'cursor_end': cursor_pos, 'metadata': dict(),
|
||||||
|
# 'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -82,5 +206,5 @@ if __name__ == '__main__':
|
|||||||
try:
|
try:
|
||||||
from ipykernel.kernelapp import IPKernelApp
|
from ipykernel.kernelapp import IPKernelApp
|
||||||
except ImportError:
|
except ImportError:
|
||||||
from IPython.kernel.zmq.kernelapp import IPKernelApp
|
from jupyter_client.zmq.kernelapp import IPKernelApp
|
||||||
IPKernelApp.launch_instance(kernel_class=MetaKernelyap)
|
IPKernelApp.launch_instance(kernel_class=MetaKernelyap)
|
||||||
|
79
packages/python/yapex.py
Normal file
79
packages/python/yapex.py
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
|
||||||
|
# this class is not being used
|
||||||
|
# we rely on namedtuples instead.
|
||||||
|
class T(tuple):
|
||||||
|
"""Represents a non-interned Prolog atom"""
|
||||||
|
def __new__(self, s, tple):
|
||||||
|
self.tuple.__new__(self, tple)
|
||||||
|
self.name = s
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return "yapex.T(" + self.name + " , " + tuple.__repr__(self) + ")"
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return str(self.name) + str(self.tuple)
|
||||||
|
|
||||||
|
|
||||||
|
def query_prolog(engine, s):
|
||||||
|
q = engine.query(s)
|
||||||
|
ask = True
|
||||||
|
while q.next():
|
||||||
|
vs = q.namedVarsCopy()
|
||||||
|
wrote = False
|
||||||
|
if vs:
|
||||||
|
i = 0
|
||||||
|
for eq in vs:
|
||||||
|
name = eq[0]
|
||||||
|
bind = eq[1]
|
||||||
|
if bind.isVar():
|
||||||
|
var = yap.YAPAtom('$VAR')
|
||||||
|
f = yap.YAPFunctor(var, 1)
|
||||||
|
bind.unify(yap.YAPApplTerm(f, (name)))
|
||||||
|
else:
|
||||||
|
i = bind.numberVars(i, True)
|
||||||
|
print(name.text() + " = " + bind.text())
|
||||||
|
wrote = True
|
||||||
|
print("yes")
|
||||||
|
if q.deterministic():
|
||||||
|
q.close()
|
||||||
|
return
|
||||||
|
if ask:
|
||||||
|
s = input("more(;/y), all(!/a), no ?").lstrip()
|
||||||
|
if s.startswith(';') or s.startswith('y'):
|
||||||
|
continue
|
||||||
|
elif s.startswith('#'):
|
||||||
|
exec(s.lstrip('#'))
|
||||||
|
elif s.startswith('a'):
|
||||||
|
ask = False
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
print("No (more) answers")
|
||||||
|
q.close()
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
def live():
|
||||||
|
engine = yap.YAPEngine()
|
||||||
|
loop = True
|
||||||
|
while loop:
|
||||||
|
try:
|
||||||
|
s = input("?- ")
|
||||||
|
if not s:
|
||||||
|
loop = False
|
||||||
|
query_prolog(engine, s)
|
||||||
|
except SyntaxError as err:
|
||||||
|
print("Syntax Error error: {0}".format(err))
|
||||||
|
except EOFError:
|
||||||
|
return
|
||||||
|
except RuntimeError as err:
|
||||||
|
print("YAP Execution Error: {0}".format(err))
|
||||||
|
except ValueError:
|
||||||
|
print("Could not convert data to an integer.")
|
||||||
|
except:
|
||||||
|
print("Unexpected error:", sys.exc_info()[0])
|
||||||
|
raise
|
||||||
|
|
||||||
|
#
|
||||||
|
# initialize engine
|
||||||
|
# engine = yap.YAPEngine();
|
||||||
|
# engine = yap.YAPEngine(yap.YAPParams());
|
Reference in New Issue
Block a user