python kernel

This commit is contained in:
Vitor Santos Costa 2017-08-27 22:24:34 +01:00
parent b1067dcc34
commit 3239778cf5
5 changed files with 184 additions and 171 deletions

View File

@ -0,0 +1,160 @@
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
from setuptools import setup
from setuptools.extension import Extension
from codecs import open
from os import path, makedirs, walk
from shutil import copytree, rmtree, copy2, move
from glob import glob
from pathlib import Path
import platform
import os.path
# the name of the package
name = 'YAP4PY'
#-----------------------------------------------------------------------------
# Minimal Python version sanity check
#-----------------------------------------------------------------------------
import sys
v = sys.version_info
if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
error = "ERROR: %s requires Python version 2.7 or 3.3 or above." % name
print(error, file=sys.stderr)
sys.exit(1)
PY3 = (sys.version_info[0] >= 3)
#-----------------------------------------------------------------------------
# get on with it
#-----------------------------------------------------------------------------
from codecs import open
from os import path, makedirs, walk
from shutil import copytree, rmtree, copy2, move
from glob import glob
from pathlib import Path
import platform
import os.path
import os
import shutil
from distutils.core import setup
pjoin = os.path.join
here = os.path.abspath(os.path.dirname(__file__))
pkg_root = pjoin(here, name)
my_extra_link_args = []
if platform.system() == 'Darwin':
my_extra_link_args = ['-Wl,-rpath','-Wl,${_ABS_PYTHON_MODULE_PATH}']
so = 'dylib'
#or dll in glob('yap/dlls/*'):
# move( dll ,'lib' )
cplus=['${RELATIVE_SOURCE}CXX/yapi.cpp']
py2yap=['${RELATIVE_SOURCE}packages/python/python.c',
'${RELATIVE_SOURCE}packages/python/pl2py.c',
'${RELATIVE_SOURCE}packages/python/pybips.c',
'${RELATIVE_SOURCE}packages/python/py2pl.c',
'${RELATIVE_SOURCE}packages/python/pl2pl.c',
'${RELATIVE_SOURCE}packages/python/pypreds.c'
]
native_sources = ['yapPYTHON_wrap.cxx']+py2yap+cplus
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
extensions=[Extension('_yap', native_sources,
define_macros = [('MAJOR_VERSION', '1'),
('MINOR_VERSION', '0'),
('_YAP_NOT_INSTALLED_', '1'),
('YAP_PYTHON', '1')],
runtime_library_dirs=['yap4py','${libdir}','${bindir}'],
swig_opts=['-modern', '-c++', '-py3','-I${RELATIVE_SOURCE}/CXX'],
library_dirs=['../../..','../../../CXX','../../packages/python',"${dlls}","${bindir}", '.'],
extra_link_args=my_extra_link_args,
extra_compile_args=['-g3','-O0'],
libraries=['Yap','${GMP_LIBRARIES}'],
include_dirs=['../../..',
'${GMP_INCLUDE_DIRS}',
'${RELATIVE_SOURCE}H',
'${RELATIVE_SOURCE}H/generated',
'${RELATIVE_SOURCE}OPTYap',
'${RELATIVE_SOURCE}os',
'${RELATIVE_SOURCE}include',
'${RELATIVE_SOURCE}CXX', '.']
)]
packages = ['yap4py']
def visit(d0, pls):
for (r,ds,fs) in walk('.'):
for f in fs:
f0,ext = os.path.splitext(f)
if (ext == 'yap' or ext == 'pl' or ext == 'so' or ext == 'dll' or ext == 'yss'):
pls += [os.path.join(r, f)]
for i in ds:
pls = visit(os.path.join(d0, i), pls)
return pls
package_data = {
'': visit('.',[])
}
version_ns = {'__version__':'6.3.5','minor-version':'6','minor-version':'3','patch':'5'}
setup_args = dict(
name = name,
version = version_ns['__version__'],
scripts = glob(pjoin('scripts', '*')),
packages = packages,
py_modules = ['yap'],
package_data = package_data,
include_package_data = True,
description = "YAP in Python",
author = 'YAP Development Team',
author_email = 'ipython-dev@scipy.org',
url = 'http://ipython.org',
license = 'BSD',
ext_modules = extensions,
platforms = "Linux, Mac OS X, Windows",
keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'],
classifiers = [
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
if 'develop' in sys.argv or any(a.startswith('bdist') for a in sys.argv):
import setuptools
setuptools_args = {}
install_requires = setuptools_args['install_requires'] = [
]
extras_require = setuptools_args['extras_require'] = {
'test:python_version=="2.7"': ['mock'],
'test': ['nose_warnings_filters', 'nose-timer'],
}
if 'setuptools' in sys.modules:
setup_args.update(setuptools_args)
if __name__ == '__main__':
setup(**setup_args)

View File

@ -1,171 +0,0 @@
import os.path
import sys
# debugging support.
# import pdb
from collections import namedtuple
from yap import *
class Engine( ):
def __init__(self, args=None):
def run(self, g, m=None):
if m:
self.mgoal(g, m)
else:
self.goal(g)
def f(self, g):
self.E.fun(g)
class EngineArgs( YAPEngineArgs ):
""" Interface to Engine Options class"""
class Predicate( YAPPredicate ):
""" Interface to Generic Predicate"""
class PrologPredicate( YAPPrologPredicate ):
""" Interface to Prolog Predicate"""
global engine, handler
yap_lib_path = os.path.dirname(__file__)
use_module = namedtuple('use_module', 'file')
bindvars = namedtuple('bindvars', 'list')
library = namedtuple('library', 'list')
v = namedtuple( 'v', 'slot')
yap_query = namedtuple( 'yap_query', 'query owner')
jupyter_query = namedtuple( 'jupyter_query', 'vars dict')
python_query = namedtuple( 'python_query', 'vars dict')
yapi_query = namedtuple( 'yapi_query', 'vars dict')
show_answer = namedtuple( 'show_answer', 'vars dict')
set_prolog_flag = namedtuple('set_prolog_flag', 'flag new_value')
def v():
return yap.YAPVarTerm()
def numbervars( q ):
Dict = {}
if True:
engine.goal(show_answer( q.namedVars(), Dict))
return Dict
rc = q.namedVarsVector()
q.r = q.goal().numbervars()
print( rc )
o = []
for i in rc:
if len(i) == 2:
do = str(i[0]) + " = " + str( i[1] ) + "\n"
o += do
print(do)
else:
do = str(i[0]) + " = " + str( i[1] ) + "\n"
o += do
print(do)
return o
def answer(q):
try:
v = q.next()
if v:
print( bindings )
return v
except Exception as e:
print(e.args[1])
return False
def query_prolog(engine, s):
import pdb; pdb.set_trace()
#
# construct a query from a one-line string
# q is opaque to Python
bindings = {}
q = engine.query(python_query(s, bindings))
# 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
while answer(q):
# deterministic = one solution
if q.deterministic():
# done
q.close()
return True, True
if ask:
s = input("more(;), all(*), no(\\n), python(#) ?").lstrip()
if s.startswith(';') or s.startswith('y'):
continue
elif s.startswith('#'):
try:
exec(s.lstrip('#'))
except:
raise
elif s.startswith('*') or s.startswith('a'):
ask = False
continue
else:
break
print("No (more) answers")
q.close()
return
def live(**kwargs):
loop = True
while loop:
try:
s = input("?- ")
if not s:
loop = False
else:
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
engine.close()
def boot_yap(**kwargs):
args = EngineArgs()
yap_lib_path = os.path.dirname(__file__)
args.setYapShareDir(os.path.join(yap_lib_path,"prolog"))
args.setYapLibDir(yap_lib_path)
args.setSavedState(os.path.join(yap_lib_path,"startup.yss"))
engine = YAPEngine(args)
engine.goal( set_prolog_flag('verbose', 'silent' ) )
engine.goal( use_module(library('yapi') ) )
retun engine
#
# initialize engine
# engine = yap.YAPEngine();
# engine = yap.YAPEngine(yap.YAPParams());
#
#
if __name__ == "__main__":
engine = boot_yap()
handler = numbervars
live()

View File

@ -0,0 +1,24 @@
# encoding: utf-8
"""Simple function to call to get the current InteractiveShell instance
"""
#-----------------------------------------------------------------------------
# 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_kernel.interactiveshell import YAPInteractive
if YAPInteractive.initialized():
return YAPInteractive.instance()