update Python

This commit is contained in:
Vitor Santos Costa 2016-06-28 23:30:18 +01:00
parent ff3185b551
commit 06f5fa2614
5 changed files with 244 additions and 31 deletions

View File

@ -2,7 +2,10 @@
#CHECK: PythonLibs
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
#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})
configure_file ("setup.py.cmake" "setup.py" )
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 "")
@ -55,5 +65,7 @@ if (PYTHONLIBS_FOUND) # PYTHONLIBS_FOUND - have the Python l
DESTINATION ${libpl}
)
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} install -f
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
endif (PYTHONLIBS_FOUND)

View File

@ -372,7 +372,6 @@ python_lhs((Exp1,Exp2), O) :- !,
python_lhs(F, F).
start_python :-
init_python,
python_main_module(MRef),
assert(python_mref_cache('__main__', MRef)),
python_command('import sys'),
@ -426,6 +425,5 @@ python_assign_field(C1.E, Obj) :-
python_eval_term(C1, O1),
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 ).

View File

@ -11,7 +11,7 @@ kernel_json = {
"argv": [sys.executable,
"-m", "yap_kernel",
"-f", "{connection_file}"],
"display_name": "MetaKernel YAP %i" % (3 if PY3 else 2),
"display_name": " YAP-6.3" ,
"language": "prolog",
"name": "yap_kernel",
}
@ -19,7 +19,7 @@ kernel_json = {
class install_with_kernelspec(install):
def 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
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
@ -51,8 +51,8 @@ setup(name='yap_kernel',
classifiers = [
'Framework :: IPython',
'License :: OSI Approved :: BSD License',
'Programming Language :: YAP :: 6.3',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
'Topic :: System :: Shells',
]
)

View File

@ -2,8 +2,17 @@ from __future__ import print_function
from metakernel import MetaKernel
import sys
import signal
import yap
import yapex
import ipywidgets as widgets
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class MetaKernelyap(MetaKernel):
implementation = 'MetaKernel YAP'
@ -12,7 +21,7 @@ class MetaKernelyap(MetaKernel):
language_version = '0.1'
banner = "MetaKernel YAP"
language_info = {
'mimetype': 'text/plain',
'mimetype': 'text/prolog',
'name': 'text',
# ------ If different from 'language':
'codemirror_mode': {
@ -26,24 +35,25 @@ class MetaKernelyap(MetaKernel):
}
def __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
# reset it from the subprocess. Since kernelapp ignores SIGINT except in
# message handlers, we need to temporarily reset the SIGINT handler here
# so that yap and its children are interruptible.
#sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
#try:
sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
self.engine = yap.YAPEngine()
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())
#finally:
# signal.signal(signal.SIGINT, sig)
self.olines = banner
finally:
signal.signal(signal.SIGINT, sig)
# Register Yap function to write image data to temporary file
#self.yapwrapper.run_command(image_setup_cmd)
@ -51,27 +61,141 @@ class MetaKernelyap(MetaKernel):
def get_usage(self):
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):
if not code.strip():
return ""
lines = code.split("\n")
interrupted = False
self.doReset = True
nlines = ""
try:
if self.q is None:
self.q = self.engine.query(code.rstrip())
if self.q.next():
vs = self.q.namedVars()
if vs:
l = {}
for eq in vs:
l[eq.getArg(1)] = eq.getArg(2)
return l
for line in lines:
line = line.strip()
if line.startswith('#'):
# wait
print( "comment")
elif line.startswith('%'):
# wait
call_magic( line )
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:
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:
return 'yes'
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:
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:
from ipykernel.kernelapp import IPKernelApp
except ImportError:
from IPython.kernel.zmq.kernelapp import IPKernelApp
from jupyter_client.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=MetaKernelyap)

79
packages/python/yapex.py Normal file
View 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());