Mostly about Jupyter support.
This commit is contained in:
parent
386c88e372
commit
3802a588f9
@ -19,7 +19,7 @@
|
||||
/**
|
||||
* @file c_interface.c
|
||||
*
|
||||
* @addtogroup ChYInterface
|
||||
* @addtogroup ChYInterface
|
||||
*/
|
||||
|
||||
#ifndef C_INTERFACE_C
|
||||
@ -1702,7 +1702,6 @@ X_API bool YAP_RetryGoal(YAP_dogoalinfo *dgi) {
|
||||
bool out;
|
||||
|
||||
BACKUP_MACHINE_REGS();
|
||||
printf("before RETRY H=%p, ASP=%p, B=%p, ENV=%p, TR=%p %ld\n", HR, ASP, B, ENV, TR, LOCAL_CurSlot);
|
||||
myB = (choiceptr)(LCL0 - dgi->b);
|
||||
CP = myB->cp_cp;
|
||||
/* sanity check */
|
||||
@ -1714,7 +1713,6 @@ X_API bool YAP_RetryGoal(YAP_dogoalinfo *dgi) {
|
||||
ASP = (CELL *)B;
|
||||
LOCAL_CurSlot = dgi->EndSlot;
|
||||
out = run_emulator(PASS_REGS1);
|
||||
printf("out=%d RETRY H=%p, ASP=%p, B=%p, ENV=%p, TR=%p %ld\n", out, HR, ASP, B, ENV, TR, LOCAL_CurSlot);
|
||||
if (out) {
|
||||
dgi->EndSlot = LOCAL_CurSlot;
|
||||
} else {
|
||||
|
11
CXX/yapi.cpp
11
CXX/yapi.cpp
@ -19,6 +19,11 @@ X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, arity_t,
|
||||
YAP_Term);
|
||||
X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred,
|
||||
arity_t, arity_t);
|
||||
|
||||
#if YAP_PYTHON
|
||||
X_API bool do_init_python(void);
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
YAPAtomTerm::YAPAtomTerm(char *s)
|
||||
@ -842,7 +847,11 @@ void YAPEngine::doInit(YAP_file_type_t BootMode)
|
||||
Yap_AndroidBufp[0] = '\0';
|
||||
Yap_AndroidSz = 0;
|
||||
#endif
|
||||
yerror = YAPError();
|
||||
//yerror = YAPError();
|
||||
#if YAP_PYTHON
|
||||
|
||||
do_init_python();
|
||||
#endif
|
||||
|
||||
YAPQuery initq = YAPQuery(YAPAtom("$init_system"));
|
||||
if (initq.next())
|
||||
|
23
CXX/yapq.hh
23
CXX/yapq.hh
@ -164,16 +164,6 @@ public:
|
||||
return init_args.Embedded;
|
||||
};
|
||||
|
||||
inline void setSavedState( char *fl )
|
||||
{
|
||||
init_args.SavedState = fl;
|
||||
};
|
||||
|
||||
inline const char * getSavedState( )
|
||||
{
|
||||
return init_args.SavedState;
|
||||
};
|
||||
|
||||
inline void setStackSize( bool fl )
|
||||
{
|
||||
init_args.StackSize = fl;
|
||||
@ -220,7 +210,7 @@ public:
|
||||
return init_args.YapLibDir;
|
||||
};
|
||||
|
||||
inline void setYapShareDir( const char * fl )
|
||||
inline void setYapShareDir( const char * fl )
|
||||
{
|
||||
init_args.YapShareDir = (const char *)malloc(strlen(fl)+1);
|
||||
strcpy((char *)init_args.YapShareDir, fl);
|
||||
@ -231,6 +221,17 @@ public:
|
||||
return init_args.YapShareDir;
|
||||
};
|
||||
|
||||
inline void setSavedState( const char * fl )
|
||||
{
|
||||
init_args.SavedState = (const char *)malloc(strlen(fl)+1);
|
||||
strcpy((char *)init_args.SavedState, fl);
|
||||
};
|
||||
|
||||
inline const char * getSavedState( )
|
||||
{
|
||||
return init_args.SavedState;
|
||||
};
|
||||
|
||||
inline void setYapPrologBootFile( const char * fl )
|
||||
{
|
||||
init_args.YapPrologBootFile = (const char *)malloc(strlen(fl)+1);
|
||||
|
@ -1,62 +1,25 @@
|
||||
set (Python_ADDITIONAL_VERSIONS 3.7 3.6 3.5 3.6 3.4 )
|
||||
|
||||
find_package(PythonInterp)
|
||||
# find_package(PythonLibs)
|
||||
find_package(PythonLibs)
|
||||
|
||||
|
||||
# PYTHONLIBS_FOUND - have the Python libs been found
|
||||
# PYTHONLIBS_FOUND - have the Python libs been found
|
||||
# PYTHON_LIBRARIES - path to the python library
|
||||
# PYTHON_INCLUDE_PATH - path to where Python.h is found (deprecated)
|
||||
# PYTHON_INCLUDE_DIRS - path to where Python.h is found
|
||||
# PYTHON_DEBUG_LIBRARIES - path to the debug library (deprecated)
|
||||
# PYTHONLIBS_VERSION_STRING - version of the Python libs found (since CMake 2.8.8)
|
||||
#
|
||||
##
|
||||
#
|
||||
|
||||
execute_process ( COMMAND ${PYTHON_EXECUTABLE} -c "import sysconfig; print(
|
||||
sysconfig.get_path( 'include' ) )"
|
||||
OUTPUT_VARIABLE _ABS_PYTHON_INCLUDE_PATH
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE )
|
||||
|
||||
get_filename_component ( ABS_PYTHON_INCLUDE_PATH ${_ABS_PYTHON_INCLUDE_PATH} ABSOLUTE )
|
||||
|
||||
set ( PYTHON_INCLUDE_DIR
|
||||
${ABS_PYTHON_INCLUDE_PATH}
|
||||
CACHE "PATH" "Directory with Python.h "
|
||||
)
|
||||
|
||||
set ( PYTHON_INCLUDE_DIRS
|
||||
${ABS_PYTHON_INCLUDE_PATH}
|
||||
CACHE "PATH" "Python.h Dir (Deprecated)"
|
||||
)
|
||||
|
||||
execute_process ( COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_SOURCE_DIR}/cmake/libfind.py"
|
||||
OUTPUT_VARIABLE ABS_PYTHON_SYSLIB
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE )
|
||||
|
||||
set ( PYTHON_LIBRARY
|
||||
${ABS_PYTHON_SYSLIB}
|
||||
CACHE "FILEPATH" "Python Library"
|
||||
)
|
||||
|
||||
set ( PYTHON_LIBRARIES
|
||||
${PYTHON_LIBRARY}
|
||||
CACHE "FILEPATH" "Python Library (Deprecated)"
|
||||
)
|
||||
|
||||
if ( (EXISTS ${PYTHON_LIBRARY}) AND ( EXISTS ${PYTHON_INCLUDE_DIR}) )
|
||||
set ( PYTHONLIBS_FOUND ON
|
||||
CACHE "BOOLEAN" "Python installed")
|
||||
# else()
|
||||
|
||||
#find_package(PythonLibs)
|
||||
endif()
|
||||
|
||||
|
||||
include_directories( BEFORE ${PYTHON_INCLUDE_DIR} )
|
||||
|
||||
|
||||
include_directories( BEFORE ${PYTHON_INCLUDE_DIRS} )
|
||||
|
||||
LIST( APPEND
|
||||
CMAKE_REQUIRED_INCLUDES ${PYTHON_INCLUDE_DIR} ${CMAKE_REQUIRED_INCLUDES})
|
||||
CMAKE_REQUIRED_INCLUDES ${PYTHON_INCLUDE_DIRS} ${CMAKE_REQUIRED_INCLUDES})
|
||||
|
||||
check_include_file(Python.h HAVE_PYTHON_H)
|
||||
|
||||
@ -74,4 +37,3 @@ if (PYTHONLIBS_FOUND AND SWIG_FOUND)
|
||||
add_subdirectory(packages/python/yap_kernel)
|
||||
ENDIF()
|
||||
endif()
|
||||
|
||||
|
@ -84,17 +84,12 @@ argument" - it cannot be a free variable at the time of the call;
|
||||
|
||||
|
||||
|
||||
|
||||
@defgroup extensions YAP Extensions
|
||||
@{
|
||||
|
||||
@page Extensions YAP Extensions
|
||||
|
||||
YAP includes a number of extensions over the original Prolog
|
||||
language.
|
||||
@subpage atts
|
||||
|
||||
@}
|
||||
@subpage atts
|
||||
|
||||
@page YAPProgramming Programming in YAP
|
||||
|
||||
|
@ -9,6 +9,8 @@ set (CMAKE_POSITION_INDEPENDENT_CODE TRUE)
|
||||
|
||||
add_library (YAPPython SHARED ${PYTHON_SOURCES})
|
||||
|
||||
target_link_libraries(YAPPython libYap ${PYTHON_LIBRARY})
|
||||
|
||||
set_property( SOURCE ${PYTHON_SOURCES} APPEND PROPERTY COMPILE_DEFINITIONS YAP_KERNEL=1)
|
||||
|
||||
set (PYTHON_PL python.pl)
|
||||
|
@ -1,4 +1,3 @@
|
||||
if __name__ == '__main__':
|
||||
from yapkernel import kernelapp as app
|
||||
import pdbl pdb.set_trace()
|
||||
from yap_kernel import kernelapp as app
|
||||
app.launch_new_instance()
|
||||
|
@ -8,19 +8,16 @@ PyObject *YE(term_t t, int line, const char *file, const char *code)
|
||||
{
|
||||
char buf[1024];
|
||||
YAP_WriteBuffer(YAP_GetFromSlot(t), buf, 1023, 0);
|
||||
fprintf(stderr, "**** Warning,%s@%s:%d: failed on expression %s\n", code, file, line, buf );
|
||||
fprintf(stderr, "**** Warning,%s@%s:%d: failed on expression %s\n", code, file, line, buf);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
void YEM(const char * exp, int line, const char *file, const char *code)
|
||||
void YEM(const char *exp, int line, const char *file, const char *code)
|
||||
{
|
||||
fprintf(stderr, "**** Warning,%s@%s:%d: failed while executing %s\n", code, file, line, exp );
|
||||
fprintf(stderr, "**** Warning,%s@%s:%d: failed while executing %s\n", code, file, line, exp);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* term_to_python translates and evaluates from Prolog to Python
|
||||
*
|
||||
@ -29,112 +26,139 @@ void YEM(const char * exp, int line, const char *file, const char *code)
|
||||
*
|
||||
* @return a Python object descriptor or NULL if failed
|
||||
*/
|
||||
PyObject *term_to_python(term_t t, bool eval, PyObject *o) {
|
||||
PyObject *term_to_python(term_t t, bool eval, PyObject *o)
|
||||
{
|
||||
// o≈
|
||||
YAP_Term yt = YAP_GetFromSlot(t);
|
||||
// Yap_DebugPlWriteln(yt);
|
||||
switch (PL_term_type(t)) {
|
||||
case PL_VARIABLE: {
|
||||
if (t==0) {
|
||||
Yap_ThrowError(SYSTEM_ERROR_INTERNAL, yt, "in term_to_python");
|
||||
}
|
||||
PyObject *out = PyTuple_New(1);
|
||||
PyTuple_SET_ITEM(out, 0, PyLong_FromLong(t));
|
||||
return term_to_nametuple("v", 1, out);
|
||||
};
|
||||
case PL_ATOM: {
|
||||
switch (PL_term_type(t))
|
||||
{
|
||||
case PL_VARIABLE:
|
||||
{
|
||||
if (t == 0)
|
||||
{
|
||||
Yap_ThrowError(SYSTEM_ERROR_INTERNAL, yt, "in term_to_python");
|
||||
}
|
||||
PyObject *out = PyTuple_New(1);
|
||||
PyTuple_SET_ITEM(out, 0, PyLong_FromLong(t));
|
||||
return term_to_nametuple("v", 1, out);
|
||||
};
|
||||
case PL_ATOM:
|
||||
{
|
||||
YAP_Atom at = YAP_AtomOfTerm(yt);
|
||||
const char *s;
|
||||
|
||||
s = YAP_AtomName(at);
|
||||
if (eval) {
|
||||
if (eval)
|
||||
{
|
||||
o = PythonLookup(s, o);
|
||||
/* if (!o)
|
||||
return o;
|
||||
*/
|
||||
} else
|
||||
{
|
||||
o = PythonLookupSpecial(s);
|
||||
}
|
||||
if (o) {
|
||||
Py_INCREF( o );
|
||||
return CHECKNULL(t,o);
|
||||
}
|
||||
}
|
||||
case PL_STRING: {
|
||||
}
|
||||
else
|
||||
{
|
||||
o = PythonLookupSpecial(s);
|
||||
}
|
||||
if (o)
|
||||
{
|
||||
Py_INCREF(o);
|
||||
return CHECKNULL(t, o);
|
||||
}
|
||||
}
|
||||
case PL_STRING:
|
||||
{
|
||||
const char *s = NULL;
|
||||
if (YAP_IsAtomTerm(yt)) {
|
||||
if (YAP_IsAtomTerm(yt))
|
||||
{
|
||||
s = YAP_AtomName(YAP_AtomOfTerm(yt));
|
||||
} else if (YAP_IsStringTerm(yt)) {
|
||||
}
|
||||
else if (YAP_IsStringTerm(yt))
|
||||
{
|
||||
s = YAP_StringOfTerm(yt);
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
return CHECKNULL(t, NULL);
|
||||
}
|
||||
#if PY_MAJOR_VERSION < 3
|
||||
if (proper_ascii_string(s)) {
|
||||
PyObject *o = PyString_FromStringAndSize(s, strlen(s)) ;
|
||||
if (proper_ascii_string(s))
|
||||
{
|
||||
PyObject *o = PyString_FromStringAndSize(s, strlen(s));
|
||||
return CHECKNULL(t, o);
|
||||
} else
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
|
||||
return CHECKNULL(t,pobj);
|
||||
}
|
||||
} break;
|
||||
case PL_INTEGER: {
|
||||
{
|
||||
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
|
||||
return CHECKNULL(t, pobj);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case PL_INTEGER:
|
||||
{
|
||||
int64_t j;
|
||||
if (!PL_get_int64_ex(t, &j))
|
||||
return CHECKNULL(t,NULL);
|
||||
return CHECKNULL(t, NULL);
|
||||
#if PY_MAJOR_VERSION < 3
|
||||
PyObject *o = PyInt_FromLong(j);
|
||||
return CHECKNULL(t,o);
|
||||
return CHECKNULL(t, o);
|
||||
#else
|
||||
PyObject *o = PyLong_FromLong(j);
|
||||
return CHECKNULL(t,o);
|
||||
return CHECKNULL(t, o);
|
||||
#endif
|
||||
}
|
||||
|
||||
case PL_FLOAT: {
|
||||
case PL_FLOAT:
|
||||
{
|
||||
PyObject *out;
|
||||
double fl;
|
||||
if (!PL_get_float(t, &fl))
|
||||
return CHECKNULL(t,NULL);
|
||||
return CHECKNULL(t, NULL);
|
||||
out = PyFloat_FromDouble(fl);
|
||||
return CHECKNULL(t, out);
|
||||
}
|
||||
default: {
|
||||
default:
|
||||
{
|
||||
term_t tail = PL_new_term_ref(), arg;
|
||||
size_t len, i;
|
||||
if (PL_skip_list(t, tail, &len) && PL_get_nil(tail)) {
|
||||
if (PL_skip_list(t, tail, &len) && PL_get_nil(tail))
|
||||
{
|
||||
PyObject *out, *a;
|
||||
|
||||
arg = tail;
|
||||
out = PyList_New(len);
|
||||
if (!out)
|
||||
return CHECKNULL(t,NULL);
|
||||
return CHECKNULL(t, Py_None);
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
if (!PL_get_list(t, arg, t)) {
|
||||
for (i = 0; i < len; i++)
|
||||
{
|
||||
if (!PL_get_list(t, arg, t))
|
||||
{
|
||||
PL_reset_term_refs(tail);
|
||||
return Py_None;
|
||||
}
|
||||
a = term_to_python(arg, eval, o);
|
||||
if (a == NULL) {
|
||||
a = Py_None;
|
||||
}
|
||||
if (PyList_SetItem(out, i, a) < 0) {
|
||||
a = term_to_python(arg, eval, o);
|
||||
if (a )
|
||||
{
|
||||
if (PyList_SetItem(out, i, a) < 0)
|
||||
{
|
||||
return Py_None;
|
||||
}
|
||||
}
|
||||
}
|
||||
PL_reset_term_refs(tail);
|
||||
return CHECKNULL(t,out);
|
||||
} else {
|
||||
return CHECKNULL(t, out);
|
||||
}
|
||||
else
|
||||
{
|
||||
functor_t fun;
|
||||
PyObject *rc;
|
||||
|
||||
if (!PL_get_functor(t, &fun)) {
|
||||
if (!PL_get_functor(t, &fun))
|
||||
{
|
||||
PL_reset_term_refs(tail);
|
||||
return CHECKNULL(t,NULL);
|
||||
return CHECKNULL(t, Py_None);
|
||||
}
|
||||
if (eval)
|
||||
rc = compound_to_pyeval(t, o);
|
||||
@ -145,11 +169,12 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return CHECKNULL(t,NULL);
|
||||
return CHECKNULL(t, Py_None);
|
||||
}
|
||||
|
||||
PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o) {
|
||||
if (t==0)
|
||||
PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o)
|
||||
{
|
||||
if (t == 0)
|
||||
return NULL;
|
||||
term_t yt = YAP_InitSlot(t);
|
||||
o = term_to_python(yt, eval, o);
|
||||
@ -157,11 +182,13 @@ PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o) {
|
||||
return o;
|
||||
}
|
||||
|
||||
PyObject *deref_term_to_python(term_t t) {
|
||||
PyObject *deref_term_to_python(term_t t)
|
||||
{
|
||||
// Yap_DebugPlWrite(YAP_GetFromSlot(t)); fprintf(stderr, " here I
|
||||
// am\n");
|
||||
YAP_Term yt = YAP_GetFromSlot(t);
|
||||
if (YAP_IsVarTerm(yt)) {
|
||||
if (YAP_IsVarTerm(yt))
|
||||
{
|
||||
char s[32];
|
||||
char *o = YAP_WriteBuffer(yt, s, 31, 0);
|
||||
PyObject *p = PyUnicode_FromString(o);
|
||||
|
@ -124,7 +124,7 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
|
||||
Py_ssize_t i, sz = PyList_GET_SIZE(pVal);
|
||||
|
||||
if (sz == 0) {
|
||||
rc = rc && PL_unify_atom(t, ATOM_nil);
|
||||
rc = rc && PL_unify_nil(t);
|
||||
} else {
|
||||
for (i = 0; i < sz; i++) {
|
||||
PyObject *obj;
|
||||
|
@ -593,7 +593,7 @@ static PyStructSequence_Field pnull[] = {
|
||||
{"A19", NULL}, {"A20", NULL}, {"A21", NULL}, {"A22", NULL},
|
||||
{"A23", NULL}, {"A24", NULL}, {"A25", NULL}, {"A26", NULL},
|
||||
{"A27", NULL}, {"A28", NULL}, {"A29", NULL}, {"A29", NULL},
|
||||
{"A30", NULL}, {"A31", NULL}, {"A32", NULL}, {0}};
|
||||
{"A30", NULL}, {"A31", NULL}, {"A32", NULL}, {NULL,NULL}};
|
||||
|
||||
static PyObject *structseq_str(PyObject *iobj) {
|
||||
|
||||
@ -624,11 +624,11 @@ static PyObject *structseq_str(PyObject *iobj) {
|
||||
val = PyStructSequence_GET_ITEM(obj, i);
|
||||
repr = PyObject_Str(val);
|
||||
if (repr == NULL)
|
||||
return NULL;
|
||||
return Py_None;
|
||||
crepr = PyUnicode_AsUTF8(repr);
|
||||
if (crepr == NULL) {
|
||||
Py_DECREF(repr);
|
||||
return NULL;
|
||||
return Py_None;
|
||||
}
|
||||
|
||||
/* + 3: keep space for ", " */
|
||||
@ -724,7 +724,7 @@ static PyObject *structseq_repr(PyObject *iobj) {
|
||||
|
||||
PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *tuple) {
|
||||
PyObject *o;
|
||||
#if PY_MAJOR_VERSION >= 3
|
||||
#if PY_MAJOR_VERSION >= 3
|
||||
PyTypeObject *typp;
|
||||
PyObject *key = PyUnicode_FromString(s);
|
||||
if (py_F2P && PyDict_Contains(py_F2P, key)) {
|
||||
@ -732,36 +732,35 @@ PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *tuple) {
|
||||
Py_INCREF(typp);
|
||||
} else {
|
||||
|
||||
typp = PyMem_Malloc(sizeof(PyTypeObject));
|
||||
PyStructSequence_Desc *desc = PyMem_Malloc(sizeof(PyStructSequence_Desc));
|
||||
const char*name = PyUnicode_AsUTF8(key);
|
||||
desc->name = PyMem_Malloc(strlen(name)+1);
|
||||
strcpy(desc->name, name);
|
||||
typp = calloc(sizeof(PyTypeObject), 1);
|
||||
PyStructSequence_Desc *desc = calloc(sizeof(PyStructSequence_Desc), 1);
|
||||
desc->name = PyMem_Malloc(strlen(s)+1);
|
||||
strcpy(desc->name, s);
|
||||
Py_DECREF(key);
|
||||
desc->doc = "YAPTerm";
|
||||
desc->fields = pnull;
|
||||
desc->n_in_sequence = 32;
|
||||
desc->n_in_sequence = arity;
|
||||
if (PyStructSequence_InitType2(typp, desc) < 0)
|
||||
return NULL;
|
||||
typp->tp_str = structseq_str;
|
||||
typp->tp_repr = structseq_repr;
|
||||
typp->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
|
||||
// typp->tp_str = structseq_str;
|
||||
// typp->tp_repr = structseq_repr;
|
||||
// typp = PyStructSequence_NewType(desc);
|
||||
Py_INCREF(typp);
|
||||
Py_INCREF(desc);
|
||||
//typp->tp_flags |= Py_TPFLAGS_HEAPTYPE;
|
||||
// don't do this: we cannot add a type as an atribute.
|
||||
//PyModule_AddObject(py_Main, s, (PyObject *)typp);
|
||||
if (py_F2P)
|
||||
PyDict_SetItem(py_F2P, key, (PyObject *)typp);
|
||||
Py_INCREF(typp);
|
||||
}
|
||||
o = PyStructSequence_New(typp);
|
||||
for (arity_t i = 0; i < arity; i++) {
|
||||
PyObject *pArg = PyTuple_GET_ITEM(tuple, i);
|
||||
Py_INCREF(pArg);
|
||||
if (pArg)
|
||||
PyStructSequence_SET_ITEM(o, i, pArg);
|
||||
//PyObject_Print(pArg,stderr,0);fputc('\n',stderr);
|
||||
}
|
||||
((PyStructSequence *)o)->ob_base.ob_size = arity;
|
||||
//((PyStructSequence *)o)->ob_base.ob_size = arity;
|
||||
//PyObject_Print(o,stderr,0);fputc('\n',stderr);
|
||||
return o;
|
||||
#else
|
||||
|
@ -33,7 +33,7 @@ static void add_modules(void) {
|
||||
py_ModDict = PyObject_GetAttrString(py_Sys, "modules");
|
||||
// py_Yapex = PyImport_ImportModule("yap4py.yapi");
|
||||
// PyObject *py_Yap =
|
||||
PyImport_ImportModule("yap");
|
||||
py_Yapex = PyImport_AddModule("yap4py.yapi");
|
||||
if (py_Yapex)
|
||||
Py_INCREF(py_Yapex);
|
||||
//py_F2P = PyObject_GetAttrString(py_Yap, "globals");
|
||||
@ -97,13 +97,13 @@ foreign_t end_python(void) {
|
||||
|
||||
static bool libpython_initialized = 0;
|
||||
|
||||
bool do_init_python(void) {
|
||||
X_API bool do_init_python(void) {
|
||||
// char **argv;
|
||||
|
||||
if (libpython_initialized)
|
||||
if (libpython_initialized)
|
||||
return true;
|
||||
libpython_initialized = true;
|
||||
// PyGILState_STATE gstate = PyGILState_Ensure();
|
||||
|
||||
// PyGILState_STATE gstate = PyGILState_Ensure();
|
||||
term_t t = PL_new_term_ref();
|
||||
if (!python_in_python)
|
||||
Py_Initialize();
|
||||
@ -113,11 +113,12 @@ bool do_init_python(void) {
|
||||
install_pl2pl();
|
||||
// PyGILState_Release(gstate);
|
||||
add_modules();
|
||||
return !python_in_python;
|
||||
return true;
|
||||
|
||||
}
|
||||
X_API bool init_python(void) {
|
||||
|
||||
if (python_in_python)
|
||||
return true;
|
||||
return do_init_python();
|
||||
}
|
||||
|
||||
|
@ -182,7 +182,7 @@ extern install_t install_pypreds(void);
|
||||
extern install_t install_pl2pl(void);
|
||||
|
||||
X_API extern bool init_python(void);
|
||||
extern bool do_init_python(void);
|
||||
X_API extern bool do_init_python(void);
|
||||
|
||||
extern PyObject PyInit_yap(void);
|
||||
|
||||
|
@ -5,26 +5,14 @@ INCLUDE(NewUseSWIG)
|
||||
|
||||
include(FindPythonModule)
|
||||
|
||||
set (PROLOG_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/yapi.yap)
|
||||
set (PYTHON_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/yapi.py ${CMAKE_CURRENT_SOURCE_DIR}/__init__.py ${CMAKE_CURRENT_SOURCE_DIR}/__main__.py)
|
||||
|
||||
file(RELATIVE_PATH RELATIVE_SOURCE ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR})
|
||||
|
||||
configure_file("setup.py.cmake" ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
|
||||
configure_file("setup.py.in" ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
|
||||
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
|
||||
foreach(i ${pl_library})
|
||||
get_filename_component(j ${i} NAME)
|
||||
configure_file(${i} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/${j})
|
||||
endforeach()
|
||||
foreach(i ${pl_boot_library})
|
||||
get_filename_component(j ${i} NAME)
|
||||
configure_file(${i} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/pl/${j})
|
||||
endforeach()
|
||||
foreach(i ${pl_os_library})
|
||||
get_filename_component(j ${i} NAME)
|
||||
configure_file(${i} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/os/${j})
|
||||
endforeach()
|
||||
configure_file("${CMAKE_SOURCE_DIR}/README.md" ${CMAKE_CURRENT_BINARY_DIR}/README)
|
||||
configure_file("__init__.py" ${CMAKE_CURRENT_BINARY_DIR}/yap4py/__init__.py)
|
||||
configure_file("yapi.py" ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yapi.py)
|
||||
configure_file("yapi.yap" ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/yapi.yap)
|
||||
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/YAP4PY.md" ${CMAKE_CURRENT_BINARY_DIR}/README)
|
||||
|
||||
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
|
||||
|
||||
@ -33,12 +21,12 @@ INCLUDE_DIRECTORIES("${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_SOURCE_DIR}/CXX")
|
||||
SET_SOURCE_FILES_PROPERTIES(../../swig/yap.i PROPERTIES CPLUSPLUS ON)
|
||||
SET_SOURCE_FILES_PROPERTIES(../../swig/yap.i PROPERTIES SWIG_FLAGS "-O;-py3")
|
||||
SET_SOURCE_FILES_PROPERTIES(../../swiyap.i PROPERTIES SWIG_MODULE_NAME yap)
|
||||
SET_SOURCE_FILES_PROPERTIES(../../yap.i PROPERTIES OUTPUT_NAME yap)
|
||||
#SET_SOURCE_FILES_PROPERTIES(../../swi/yap.i PROPERTIES OUTPUT_NAME yap)
|
||||
|
||||
SWIG_ADD_LIBRARY(Py2YAP LANGUAGE python SHARED SOURCES ../../swig/yap.i )
|
||||
if (WIN32)
|
||||
SWIG_LINK_LIBRARIES(Py2YAP YAPPython libYap ${PYTHON_LIBRARIES} )
|
||||
else()
|
||||
else()
|
||||
SWIG_LINK_LIBRARIES( Py2YAP libYap YAP++ YAPPython ${PYTHON_LIBRARIES} )
|
||||
endif()
|
||||
set_target_properties ( ${SWIG_MODULE_Py2YAP_REAL_NAME}
|
||||
@ -50,22 +38,6 @@ if (WIN32)
|
||||
)
|
||||
# inform we are compiling YAP
|
||||
# s used in MSYS
|
||||
|
||||
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import sysconfig; print( sysconfig.get_path( 'platlib' ) )"
|
||||
OUTPUT_VARIABLE _ABS_PYTHON_MODULE_PATH
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
|
||||
get_filename_component(ABS_PYTHON_MODULE_PATH ${_ABS_PYTHON_MODULE_PATH} ABSOLUTE)
|
||||
file(RELATIVE_PATH _REL_PYTHON_MODULE_PATH ${CMAKE_INSTALL_PREFIX} ${_ABS_PYTHON_MODULE_PATH})
|
||||
#
|
||||
# set ( PYTHON_MODULE_PATH
|
||||
# ${ABS_PYTHON_MODULE_PATH}
|
||||
# )
|
||||
#
|
||||
# INSTALL ( FILES ${CMAKE_CURRENT_BINARY_DIR}/yap.py DESTINATION ${PYTHON_MODULE_PATH} )
|
||||
# INSTALL ( FILES ${CMAKE_CURRENT_SOURCE_DIR}/yapi.py DESTINATION ${PYTHON_MODULE_PATH} )
|
||||
# INSTALL ( FILES ${CMAKE_CURRENT_SOURCE_DIR}/yapi.yap DESTINATION ${libpl} )
|
||||
#
|
||||
#
|
||||
# INSTALL ( TARGETS ${SWIG_MODULE_Py2YAP_REAL_NAME}
|
||||
@ -81,28 +53,31 @@ if (WIN32)
|
||||
$<TARGET_FILE:tries>
|
||||
$<TARGET_FILE:itries>
|
||||
$<TARGET_FILE:sys>
|
||||
$<TARGET_FILE:real>
|
||||
$<TARGET_FILE:yap_random>)
|
||||
if (TARGET real)
|
||||
list( APPEND dlls $<TARGET_FILE:real>
|
||||
)
|
||||
endif()
|
||||
|
||||
file( MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/pl )
|
||||
file( MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/os )
|
||||
|
||||
add_custom_target( YAP4PY ALL
|
||||
)
|
||||
|
||||
|
||||
add_custom_command (TARGET YAP4PY
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${dlls} ${CMAKE_BINARY_DIR}/libYap${CMAKE_SHARED_LIBRARY_SUFFIX} ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${CMAKE_CURRENT_BINARY_DIR}/yap4py
|
||||
COMMAND ${PYTHON_EXECUTABLE} setup.py clean sdist bdist_wheel
|
||||
VERBATIM
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${dlls} ${CMAKE_BINARY_DIR}/libYap${CMAKE_SHARED_LIBRARY_SUFFIX} ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${CMAKE_CURRENT_BINARY_DIR}/yap4py
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${pl_library} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${PYTHON_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/yap4py
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/yapi.yap ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${pl_library} ${PROLOG_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${pl_boot_library} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/pl
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${pl_os_library} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/prolog/os
|
||||
COMMAND ${PYTHON_EXECUTABLE} setup.py sdist bdist_wheel
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
DEPENDS ${CMAKE_BINARY_DIR}/${YAP_STARTUP} libYap ${dlls} ${pl_library} ${pl_boot_library} ${pl_os_library} yapi.py}
|
||||
)
|
||||
DEPENDS STARTUP ${dlls} ${PYTHON_SOURCES} ${PROLOG_SOURCES} setup.py ${SWIG_MODULE_Py2YAP_REAL_NAME} )
|
||||
|
||||
|
||||
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-index -f dist yap4py
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})"
|
||||
DEPENDS Py4YAP${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${dlls} )
|
||||
DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${dlls} )
|
||||
|
||||
|
||||
if (WITH_DOCS AND DOXYGEN_FOUND)
|
||||
|
@ -1,7 +1,9 @@
|
||||
include COPYING.md
|
||||
include CONTRIBUTING.md
|
||||
# include COPYING.md
|
||||
# include CONTRIBUTING.md
|
||||
include README.md
|
||||
|
||||
recursive-include * *.*
|
||||
|
||||
# Documentation
|
||||
graft docs
|
||||
exclude docs/\#*
|
||||
|
@ -45,7 +45,7 @@ here = path.abspath(path.dirname(__file__))
|
||||
|
||||
# Get the long description from the README file
|
||||
|
||||
extensions=[Extension('_yap', python_sources,
|
||||
extensions=[Extension '_yap', python_sources,
|
||||
define_macros = [('MAJOR_VERSION', '1'),
|
||||
('MINOR_VERSION', '0'),
|
||||
('_YAP_NOT_INSTALLED_', '1'),
|
||||
@ -54,7 +54,7 @@ extensions=[Extension('_yap', python_sources,
|
||||
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=['-g'],
|
||||
extra_compile_args=['-g3','-O0'],
|
||||
libraries=['Yap','${GMP_LIBRARIES}'],
|
||||
include_dirs=['../../..',
|
||||
'${GMP_INCLUDE_DIRS}',
|
||||
@ -86,12 +86,12 @@ setup(
|
||||
'Programming Language :: Python :: 3.6',
|
||||
'Programming Language :: Python :: 3.7'],
|
||||
keywords=['Logic Programing'],
|
||||
#spackage_data={'': ['yap']},
|
||||
#package_data={'yap4py':['*.*'] },
|
||||
include_package_data=True,
|
||||
ext_modules = extensions,
|
||||
py_modules = ['yap'],
|
||||
#py_modules = ['yap'],
|
||||
zip_safe=False,
|
||||
eager_resources = ['yap4py'],
|
||||
packages=['yap4py'] # find_packages()
|
||||
eager_resources = [''],
|
||||
#packages=['yap4py'] # find_packages()
|
||||
#package_dir = {'':'yap4py'}
|
||||
)
|
||||
|
@ -16,7 +16,7 @@ import platform
|
||||
import os.path
|
||||
|
||||
# the name of the package
|
||||
name = 'yap_kernel'
|
||||
name = 'YAP4PY'
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Minimal Python version sanity check
|
||||
@ -35,8 +35,13 @@ 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
|
||||
|
||||
@ -92,29 +97,21 @@ extensions=[Extension('_yap', native_sources,
|
||||
|
||||
packages = ['yap4py']
|
||||
|
||||
pls = []
|
||||
for (r,d,fs) in walk('dylib'):
|
||||
for f in fs:
|
||||
pls += [os.path.join(r, f)]
|
||||
for (r,d,fs) in walk('yss'):
|
||||
for f in fs:
|
||||
pls += [os.path.join(r, f)]
|
||||
for (r,d,fs) in walk('pl'):
|
||||
for f in fs:
|
||||
pls += [os.path.join(r, f)]
|
||||
for (r,d,fs) in walk('yap'):
|
||||
for f in fs:
|
||||
pls += [os.path.join(r, f)]
|
||||
|
||||
for d, _, _ in os.walk(pjoin(here, name)):
|
||||
if os.path.exists(pjoin(d, '__init__.py')):
|
||||
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))
|
||||
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 = {
|
||||
'yap4pyl': pls,
|
||||
'': visit('.',[])
|
||||
}
|
||||
|
||||
version_ns = {'__version__'='6.3','minor-version'='6','minor-version'='3','patch'='5'}
|
||||
version_ns = {'__version__':'6.3.5','minor-version':'6','minor-version':'3','patch':'5'}
|
||||
|
||||
|
||||
setup_args = dict(
|
||||
@ -124,12 +121,13 @@ setup_args = dict(
|
||||
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',
|
||||
extensions = ['extensions'],
|
||||
ext_modules = extensions,
|
||||
platforms = "Linux, Mac OS X, Windows",
|
||||
keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'],
|
||||
classifiers = [
|
||||
|
@ -14,9 +14,15 @@ library = namedtuple( 'library', 'list')
|
||||
v = namedtuple( '_', 'slot')
|
||||
|
||||
|
||||
|
||||
def numbervars( engine, l ):
|
||||
return engine.fun(bindvars(l))
|
||||
rc = engine.fun(bindvars(l))
|
||||
o = []
|
||||
for i in rc:
|
||||
if i[0] == "=":
|
||||
o = o + [i[1]]
|
||||
else:
|
||||
o = o +[i]
|
||||
return o
|
||||
|
||||
def query_prolog(engine, s):
|
||||
|
||||
@ -86,15 +92,18 @@ def query_prolog(engine, s):
|
||||
q.close()
|
||||
return
|
||||
|
||||
|
||||
def live():
|
||||
def boot_yap(**kwargs):
|
||||
yap_lib_path = os.path.dirname(__file__)
|
||||
args = yap.YAPEngineArgs()
|
||||
args.setYapShareDir(os.path.join(yap_lib_path,"prolog"))
|
||||
args.setYapLibDir(yap_lib_path)
|
||||
#args.setYapPrologBootFile(os.path.join(yap_lib_path."startup.yss"))
|
||||
args.setSavedState(os.path.join(yap_lib_path,"startup.yss"))
|
||||
engine = yap.YAPEngine(args)
|
||||
engine.goal( use_module(library('yapi') ) )
|
||||
return engine
|
||||
|
||||
def live(**kwargs):
|
||||
boot_yap(**kwargs)
|
||||
loop = True
|
||||
while loop:
|
||||
try:
|
||||
|
@ -10,11 +10,18 @@
|
||||
bindvars( [], [] ) :- !.
|
||||
bindvars( L, NL ) :-
|
||||
rb_new(T),
|
||||
% trace,
|
||||
foldl2( bind, L, NL, T, _ , 0, _),
|
||||
term_variables(NL, Vs),
|
||||
foldl( bind_new, Vs, 0, _).
|
||||
|
||||
|
||||
bind(t(_,t(X,Y)), Z, T0, T, N1, N2) :-
|
||||
!,
|
||||
bind(X=Y, Z, T0, T, N1, N2).
|
||||
bind(tuple(_,tuple(X,Y)), Z, T0, T, N1, N2) :-
|
||||
!,
|
||||
bind(X=Y, Z, T0, T, N1, N2).
|
||||
bind(X=Y, X=X, T0, T, N, N) :-
|
||||
var(Y),
|
||||
!,
|
||||
|
@ -1,23 +1,60 @@
|
||||
|
||||
set (EXTRAS
|
||||
MANIFEST.in
|
||||
YAP_KERNEL.md
|
||||
)
|
||||
|
||||
set (PYTHON_SOURCES
|
||||
__main__.py
|
||||
__init__.py
|
||||
setup.py
|
||||
_version.py
|
||||
interactiveshell.py
|
||||
kernelapp.py
|
||||
kernelspec.py
|
||||
yapkernel.py )
|
||||
|
||||
yap_kernel_launcher.py
|
||||
data_kernelspec/kernel.json
|
||||
yap_kernel/__init__.py
|
||||
yap_kernel/__main__.py
|
||||
yap_kernel/_version.py
|
||||
yap_kernel/codeutil.py
|
||||
yap_kernel/connect.py
|
||||
yap_kernel/datapub.py
|
||||
yap_kernel/displayhook.py
|
||||
yap_kernel/embed.py
|
||||
yap_kernel/eventloops.py
|
||||
yap_kernel/heartbeat.py
|
||||
yap_kernel/interactiveshell.py
|
||||
yap_kernel/iostream.py
|
||||
yap_kernel/jsonutil.py
|
||||
yap_kernel/kernelapp.py
|
||||
yap_kernel/kernelbase.py
|
||||
yap_kernel/kernelspec.py
|
||||
yap_kernel/log.py
|
||||
yap_kernel/parentpoller.py
|
||||
yap_kernel/pickleutil.py
|
||||
yap_kernel/serialize.py
|
||||
yap_kernel/yapkernel.py
|
||||
yap_kernel/zmqshell.py
|
||||
yap_kernel/comm/__init__.py
|
||||
yap_kernel/comm/comm.py
|
||||
yap_kernel/comm/manager.py
|
||||
yap_kernel/gui/__init__.py
|
||||
yap_kernel/gui/gtk3embed.py
|
||||
yap_kernel/gui/gtkembed.py
|
||||
yap_kernel/inprocess/__init__.py
|
||||
yap_kernel/inprocess/blocking.py
|
||||
yap_kernel/inprocess/channels.py
|
||||
yap_kernel/inprocess/client.py
|
||||
yap_kernel/inprocess/constants.py
|
||||
yap_kernel/inprocess/ipkernel.py
|
||||
yap_kernel/inprocess/manager.py
|
||||
yap_kernel/inprocess/socket.py
|
||||
yap_kernel/pylab/__init__.py
|
||||
yap_kernel/pylab/backend_inline.py
|
||||
yap_kernel/pylab/config.py
|
||||
)
|
||||
|
||||
foreach(i ${PYTHON_SOURCES})
|
||||
configure_file(${i} ${CMAKE_CURRENT_BINARY_DIR}/${i})
|
||||
endforeach()
|
||||
configure_file("setup.py" ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
|
||||
configure_file("MANIFEST.in" ${CMAKE_CURRENT_BINARY_DIR}/MANIFEST.in)
|
||||
foreach(i ${PYTHON_SOURCES})
|
||||
configure_file(${i} ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/${i})
|
||||
endforeach()
|
||||
configure_file("_version.py" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/_version.py)
|
||||
configure_file("YAP_KERNEL.md" ${CMAKE_CURRENT_BINARY_DIR}/README)
|
||||
configure_file("yap_kernel/_version.py" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/_version.py )
|
||||
configure_file("${CMAKE_SOURCE_DIR}/docs/icons/yap_32x32x32.png" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png)
|
||||
configure_file("${CMAKE_SOURCE_DIR}/docs/icons/yap_64x64x32.png" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png)
|
||||
configure_file("${CMAKE_SOURCE_DIR}/misc/editors/prolog.js" ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js)
|
||||
@ -27,9 +64,7 @@ set(SETUP_PY "${CMAKE_CURRENT_BINARY_DIR}/setup.py")
|
||||
set( PYTHON_INSTALL sdist bdist_wheel)
|
||||
|
||||
add_custom_target( YAPKernel ALL
|
||||
)
|
||||
|
||||
add_custom_command (TARGET YAPKernel
|
||||
COMMAND ${PYTHON_EXECUTABLE} setup.py clean sdist bdist_wheel
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
DEPENDS libYap ${SWIG_MODULE_Py2YAP_REAL_NAME}
|
||||
@ -41,4 +76,3 @@ install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --no-i
|
||||
install(FILES jupyter.yap
|
||||
DESTINATION ${libpl}
|
||||
)
|
||||
|
||||
|
@ -1,24 +1,14 @@
|
||||
include COPYING.md
|
||||
include CONTRIBUTING.md
|
||||
#include COPYING.md
|
||||
#include CONTRIBUTING.md
|
||||
include README.md
|
||||
|
||||
|
||||
# Documentation
|
||||
graft docs
|
||||
exclude docs/\#*
|
||||
|
||||
# Examples
|
||||
graft examples
|
||||
|
||||
# docs subdirs we want to skip
|
||||
prune docs/build
|
||||
prune docs/gh-pages
|
||||
prune docs/dist
|
||||
|
||||
graft
|
||||
# Patterns to exclude from any directory
|
||||
global-exclude *~
|
||||
global-exclude *.pyc
|
||||
global-exclude *.pyo
|
||||
global-exclude .git
|
||||
global-exclude .ipynb_checkpoints
|
||||
|
||||
prune data_kernelspec
|
||||
|
@ -1,2 +0,0 @@
|
||||
from ._version import version_info, __version__, kernel_protocol_version_info, kernel_protocol_version
|
||||
from ipykernel.connect import *
|
@ -1,4 +0,0 @@
|
||||
|
||||
if __name__ == '__main__':
|
||||
from yap_kernel.kernelapp import launch_new_instance
|
||||
launch_new_instance()
|
@ -1,5 +0,0 @@
|
||||
version_info = (4, 4, 1)
|
||||
__version__ = '.'.join(map(str, version_info))
|
||||
|
||||
kernel_protocol_version_info = (5, 0)
|
||||
kernel_protocol_version = '%s.%s' % kernel_protocol_version_info
|
Binary file not shown.
Binary file not shown.
@ -1,225 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""YAP Stuff for Main IPython class."""
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
|
||||
# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
|
||||
# Copyright (C) 2008-2011 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.
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
import __future__
|
||||
import abc
|
||||
import ast
|
||||
import atexit
|
||||
import functools
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import signal
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
import types
|
||||
import subprocess
|
||||
import warnings
|
||||
import yap
|
||||
import yap4py.yapi
|
||||
from io import open as io_open
|
||||
|
||||
from pickleshare import PickleShareDB
|
||||
|
||||
from traitlets.config.configurable import SingletonConfigurable
|
||||
from IPython.core import oinspect
|
||||
from IPython.core import magic
|
||||
from IPython.core import page
|
||||
from IPython.core import prefilter
|
||||
from IPython.core import shadowns
|
||||
from IPython.core import ultratb
|
||||
from IPython.core import interactiveshell
|
||||
from IPython.core.alias import Alias, AliasManager
|
||||
from IPython.core.autocall import ExitAutocall
|
||||
from IPython.core.builtin_trap import BuiltinTrap
|
||||
from IPython.core.events import EventManager, available_events
|
||||
from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
|
||||
from IPython.core.debugger import Pdb
|
||||
from IPython.core.display_trap import DisplayTrap
|
||||
from IPython.core.displayhook import DisplayHook
|
||||
from IPython.core.displaypub import DisplayPublisher
|
||||
from IPython.core.error import InputRejected, UsageError
|
||||
from IPython.core.extensions import ExtensionManager
|
||||
from IPython.core.formatters import DisplayFormatter
|
||||
from IPython.core.history import HistoryManager
|
||||
from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
|
||||
from IPython.core.logger import Logger
|
||||
from IPython.core.macro import Macro
|
||||
from IPython.core.payload import PayloadManager
|
||||
from IPython.core.prefilter import PrefilterManager
|
||||
from IPython.core.profiledir import ProfileDir
|
||||
from IPython.core.usage import default_banner
|
||||
from IPython.core.interactiveshell import InteractiveShellABC, InteractiveShell, ExecutionResult
|
||||
from IPython.testing.skipdoctest import skip_doctest
|
||||
from IPython.utils import PyColorize
|
||||
from IPython.utils import io
|
||||
from IPython.utils import py3compat
|
||||
from IPython.utils import openpy
|
||||
from IPython.utils.decorators import undoc
|
||||
from IPython.utils.io import ask_yes_no
|
||||
from IPython.utils.ipstruct import Struct
|
||||
from IPython.paths import get_ipython_dir
|
||||
from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
|
||||
from IPython.utils.process import system, getoutput
|
||||
from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
|
||||
with_metaclass, iteritems)
|
||||
from IPython.utils.strdispatch import StrDispatch
|
||||
from IPython.utils.syspathcontext import prepended_to_syspath
|
||||
from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
|
||||
from IPython.utils.tempdir import TemporaryDirectory
|
||||
from traitlets import (
|
||||
Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
|
||||
observe, default,
|
||||
)
|
||||
from warnings import warn
|
||||
from logging import error
|
||||
from collections import namedtuple
|
||||
|
||||
|
||||
use_module = namedtuple( 'use_module', 'file')
|
||||
bindvars = namedtuple( 'bindvars', 'list')
|
||||
library = namedtuple( 'library', 'list')
|
||||
v = namedtuple( '_', 'slot')
|
||||
|
||||
class YAPInteractiveShell:
|
||||
"""An enhanced, interactive shell for YAP."""
|
||||
|
||||
def __init__(self, kernel):
|
||||
|
||||
pjoin = os.path.join
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
yap_lib_path = pjoin(here, "../yap4py/prolog" )
|
||||
yap_dll_path = pjoin(here, "../yap4py" )
|
||||
args = yap.YAPEngineArgs()
|
||||
args.setYapLibDir(yap_dll_path)
|
||||
args.setYapShareDir(yap_lib_path)
|
||||
#args.setYapPrologBootFile(os.path.join(yap_lib_path."startup.yss"))
|
||||
self.yapeng = yap.YAPEngine( args )
|
||||
self.q = None
|
||||
self.yapeng.goal( use_module( library('yapi') ) )
|
||||
self.shell = kernel.shell
|
||||
self.shell.run_cell = self.run_cell
|
||||
|
||||
|
||||
def closeq(self):
|
||||
if self.q:
|
||||
self.q.close()
|
||||
self.q = None
|
||||
|
||||
def run_cell(self, s, 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`
|
||||
"""
|
||||
|
||||
def numbervars(self, l):
|
||||
return self.yapeng.fun(bindvars(l))
|
||||
|
||||
result = ExecutionResult()
|
||||
|
||||
if (not s) or s.isspace():
|
||||
self.shell.last_execution_succeeded = True
|
||||
return result
|
||||
|
||||
if store_history:
|
||||
result.execution_count = self.shell.execution_count
|
||||
|
||||
def error_before_exec(value):
|
||||
result.error_before_exec = value
|
||||
self.shell.last_execution_succeeded = False
|
||||
return result
|
||||
|
||||
|
||||
if not self.q:
|
||||
try:
|
||||
self.q = self.yapeng.query(s)
|
||||
except SyntaxError:
|
||||
return error_before_exec( sys.exc_info()[1])
|
||||
|
||||
cell = s # cell has to exist so it can be stored/logged
|
||||
|
||||
# Store raw and processed history
|
||||
# if not silent:
|
||||
# self.shell..logger.log(cell, s)
|
||||
|
||||
has_raised = False
|
||||
try:
|
||||
#f = io.StringIO()
|
||||
# with redirect_stdout(f):
|
||||
run = self.q.next()
|
||||
# print('{0}'.format(f.getvalue()))
|
||||
# Execute the user code
|
||||
if run:
|
||||
myvs = self.numbervars(self.q.namedVars())
|
||||
if myvs:
|
||||
for eq in myvs:
|
||||
name = eq[0]
|
||||
binding = eq[1]
|
||||
if name != binding:
|
||||
print(name + " = " + str(binding))
|
||||
else:
|
||||
print("yes")
|
||||
if self.q.deterministic():
|
||||
self.closeq()
|
||||
else:
|
||||
print("No (more) answers")
|
||||
self.closeq()
|
||||
except:
|
||||
result.error_in_exec = sys.exc_info()[1]
|
||||
# self.showtraceback()
|
||||
has_raised = True
|
||||
self.closeq()
|
||||
|
||||
|
||||
self.shell.last_execution_succeeded = not has_raised
|
||||
result.result = self.shell.last_execution_succeeded
|
||||
print( self.q )
|
||||
# Reset this so later displayed values do not modify the
|
||||
# ExecutionResult
|
||||
# self.displayhook.exec_result = None
|
||||
|
||||
#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.shell.execution_count += 1
|
||||
|
||||
return result
|
@ -1,18 +0,0 @@
|
||||
|
||||
:- use_module(library(python)).
|
||||
|
||||
:- if( current_prolog_flag(apple, true) ).
|
||||
|
||||
:- putenv( 'LC_CTYPE', 'en_us:UTF-8').
|
||||
|
||||
plot_inline :-
|
||||
X := self.inline_plotting,
|
||||
nb_setval(inline, X ),
|
||||
X = true,
|
||||
!,
|
||||
:= (
|
||||
import( matplotlib ),
|
||||
matplotlib.use( `nbagg` )
|
||||
).
|
||||
|
||||
:- endif.
|
@ -1,488 +0,0 @@
|
||||
"""An Application for launching a kernel"""
|
||||
|
||||
# Copyright (c) IPython Development Team.
|
||||
# Distributed under the terms of the Modified BSD License.
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
import atexit
|
||||
import os
|
||||
import sys
|
||||
import signal
|
||||
import traceback
|
||||
import logging
|
||||
|
||||
from tornado import ioloop
|
||||
import zmq
|
||||
from zmq.eventloop import ioloop as zmq_ioloop
|
||||
from zmq.eventloop.zmqstream import ZMQStream
|
||||
from ipykernel.zmqshell import ZMQInteractiveShell
|
||||
|
||||
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 IPython.utils import io
|
||||
from ipython_genutils.path import filefind, ensure_dir_exists
|
||||
from traitlets import (
|
||||
Any, Instance, Dict, Unicode, Integer, Bool, DottedObjectName, Type, default
|
||||
)
|
||||
from ipython_genutils.importstring import import_item
|
||||
from jupyter_core.paths import jupyter_runtime_dir
|
||||
from jupyter_client import write_connection_file
|
||||
from jupyter_client.connect import ConnectionFileMixin
|
||||
|
||||
# local imports
|
||||
from ipykernel.iostream import IOPubThread
|
||||
from ipykernel.heartbeat import Heartbeat
|
||||
from yap_kernel.yapkernel import YAPKernel
|
||||
from ipykernel.parentpoller import ParentPollerUnix, ParentPollerWindows
|
||||
from jupyter_client.session import (
|
||||
Session, session_flags, session_aliases,
|
||||
)
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Flags and Aliases
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
kernel_aliases = dict(base_aliases)
|
||||
kernel_aliases.update({
|
||||
'ip' : 'YAPKernelApp.ip',
|
||||
'hb' : 'YAPKernelApp.hb_port',
|
||||
'shell' : 'YAPKernelApp.shell_port',
|
||||
'iopub' : 'YAPKernelApp.iopub_port',
|
||||
'stdin' : 'YAPKernelApp.stdin_port',
|
||||
'control' : 'YAPKernelApp.control_port',
|
||||
'f' : 'YAPKernelApp.connection_file',
|
||||
'transport': 'YAPKernelApp.transport',
|
||||
})
|
||||
|
||||
kernel_flags = dict(base_flags)
|
||||
kernel_flags.update({
|
||||
'no-stdout' : (
|
||||
{'YAPKernelApp' : {'no_stdout' : True}},
|
||||
"redirect stdout to the null device"),
|
||||
'no-stderr' : (
|
||||
{'YAPKernelApp' : {'no_stderr' : True}},
|
||||
"redirect stderr to the null device"),
|
||||
'pylab' : (
|
||||
{'YAPKernelApp' : {'pylab' : 'auto'}},
|
||||
"""Pre-load matplotlib and numpy for interactive use with
|
||||
the default matplotlib backend."""),
|
||||
})
|
||||
|
||||
# inherit flags&aliases for any IPython shell apps
|
||||
kernel_aliases.update(shell_aliases)
|
||||
kernel_flags.update(shell_flags)
|
||||
|
||||
# inherit flags&aliases for Sessions
|
||||
kernel_aliases.update(session_aliases)
|
||||
kernel_flags.update(session_flags)
|
||||
|
||||
_ctrl_c_message = """\
|
||||
NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
|
||||
|
||||
To exit, you will have to explicitly quit this process, by either sending
|
||||
"quit" from a client, or using Ctrl-\\ in UNIX-like environments.
|
||||
|
||||
To read more about this, see https://github.com/ipython/ipython/issues/2049
|
||||
|
||||
"""
|
||||
|
||||
#-----------------------------------------------------------------------------
|
||||
# Application class for starting an IPython Kernel
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
class YAPKernelApp(BaseIPythonApplication, InteractiveShellApp,
|
||||
ConnectionFileMixin):
|
||||
name='YAP-kernel'
|
||||
aliases = Dict(kernel_aliases)
|
||||
flags = Dict(kernel_flags)
|
||||
classes = [YAPKernel, ZMQInteractiveShell, ProfileDir, Session]
|
||||
# the kernel class, as an importstring
|
||||
kernel_class = Type('yap_kernel.yapkernel.YAPKernel',
|
||||
klass='ipykernel.kernelbase.Kernel',
|
||||
help="""The Kernel subclass to be used.
|
||||
|
||||
This should allow easy re-use of the YAPKernelApp entry point
|
||||
to configure and launch kernels other than IPython's own.
|
||||
""").tag(config=True)
|
||||
kernel = Any()
|
||||
poller = Any() # don't restrict this even though current pollers are all Threads
|
||||
heartbeat = Instance(Heartbeat, allow_none=True)
|
||||
ports = Dict()
|
||||
|
||||
subcommands = {
|
||||
'install': (
|
||||
'yap_kernel.kernelspec.InstallYAPKernelSpecApp',
|
||||
'Install the YAP kernel'
|
||||
),
|
||||
}
|
||||
|
||||
# connection info:
|
||||
connection_dir = Unicode()
|
||||
|
||||
@default('connection_dir')
|
||||
def _default_connection_dir(self):
|
||||
return jupyter_runtime_dir()
|
||||
|
||||
@property
|
||||
def abs_connection_file(self):
|
||||
if os.path.basename(self.connection_file) == self.connection_file:
|
||||
return os.path.join(self.connection_dir, self.connection_file)
|
||||
else:
|
||||
return self.connection_file
|
||||
|
||||
# streams, etc.
|
||||
no_stdout = Bool(False, help="redirect stdout to the null device").tag(config=True)
|
||||
no_stderr = Bool(False, help="redirect stderr to the null device").tag(config=True)
|
||||
outstream_class = DottedObjectName('ipykernel.iostream.OutStream',
|
||||
help="The importstring for the OutStream factory").tag(config=True)
|
||||
displayhook_class = DottedObjectName('ipykernel.displayhook.ZMQDisplayHook',
|
||||
help="The importstring for the DisplayHook factory").tag(config=True)
|
||||
|
||||
# polling
|
||||
parent_handle = Integer(int(os.environ.get('JPY_PARENT_PID') or 0),
|
||||
help="""kill this process if its parent dies. On Windows, the argument
|
||||
specifies the HANDLE of the parent process, otherwise it is simply boolean.
|
||||
""").tag(config=True)
|
||||
interrupt = Integer(int(os.environ.get('JPY_INTERRUPT_EVENT') or 0),
|
||||
help="""ONLY USED ON WINDOWS
|
||||
Interrupt this process when the parent is signaled.
|
||||
""").tag(config=True)
|
||||
|
||||
def init_crash_handler(self):
|
||||
sys.excepthook = self.excepthook
|
||||
|
||||
def excepthook(self, etype, evalue, tb):
|
||||
# write uncaught traceback to 'real' stderr, not zmq-forwarder
|
||||
traceback.print_exception(etype, evalue, tb, file=sys.__stderr__)
|
||||
|
||||
def init_poller(self):
|
||||
if sys.platform == 'win32':
|
||||
if self.interrupt or self.parent_handle:
|
||||
self.poller = ParentPollerWindows(self.interrupt, self.parent_handle)
|
||||
elif self.parent_handle:
|
||||
self.poller = ParentPollerUnix()
|
||||
|
||||
def _bind_socket(self, s, port):
|
||||
iface = '%s://%s' % (self.transport, self.ip)
|
||||
if self.transport == 'tcp':
|
||||
if port <= 0:
|
||||
port = s.bind_to_random_port(iface)
|
||||
else:
|
||||
s.bind("tcp://%s:%i" % (self.ip, port))
|
||||
elif self.transport == 'ipc':
|
||||
if port <= 0:
|
||||
port = 1
|
||||
path = "%s-%i" % (self.ip, port)
|
||||
while os.path.exists(path):
|
||||
port = port + 1
|
||||
path = "%s-%i" % (self.ip, port)
|
||||
else:
|
||||
path = "%s-%i" % (self.ip, port)
|
||||
s.bind("ipc://%s" % path)
|
||||
return port
|
||||
|
||||
def write_connection_file(self):
|
||||
"""write connection info to JSON file"""
|
||||
cf = self.abs_connection_file
|
||||
self.log.debug("Writing connection file: %s", cf)
|
||||
write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport,
|
||||
shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port,
|
||||
iopub_port=self.iopub_port, control_port=self.control_port)
|
||||
|
||||
def cleanup_connection_file(self):
|
||||
cf = self.abs_connection_file
|
||||
self.log.debug("Cleaning up connection file: %s", cf)
|
||||
try:
|
||||
os.remove(cf)
|
||||
except (IOError, OSError):
|
||||
pass
|
||||
|
||||
self.cleanup_ipc_files()
|
||||
|
||||
def init_connection_file(self):
|
||||
if not self.connection_file:
|
||||
self.connection_file = "kernel-%s.json"%os.getpid()
|
||||
try:
|
||||
self.connection_file = filefind(self.connection_file, ['.',self.connection_dir])
|
||||
except IOError:
|
||||
self.log.debug("Connection file not found: %s", self.connection_file)
|
||||
# This means I own it, and I'll create it in this directory:
|
||||
ensure_dir_exists(os.path.dirname(self.abs_connection_file), 0o700)
|
||||
# Also, I will clean it up:
|
||||
atexit.register(self.cleanup_connection_file)
|
||||
return
|
||||
try:
|
||||
self.load_connection_file()
|
||||
except Exception:
|
||||
self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True)
|
||||
self.exit(1)
|
||||
|
||||
def init_sockets(self):
|
||||
# Create a context, a session, and the kernel sockets.
|
||||
self.log.info("Starting the kernel at pid: %i", os.getpid())
|
||||
context = zmq.Context.instance()
|
||||
# Uncomment this to try closing the context.
|
||||
# atexit.register(context.term)
|
||||
|
||||
self.shell_socket = context.socket(zmq.ROUTER)
|
||||
self.shell_socket.linger = 1000
|
||||
self.shell_port = self._bind_socket(self.shell_socket, self.shell_port)
|
||||
self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port)
|
||||
|
||||
self.stdin_socket = context.socket(zmq.ROUTER)
|
||||
self.stdin_socket.linger = 1000
|
||||
self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port)
|
||||
self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port)
|
||||
|
||||
self.control_socket = context.socket(zmq.ROUTER)
|
||||
self.control_socket.linger = 1000
|
||||
self.control_port = self._bind_socket(self.control_socket, self.control_port)
|
||||
self.log.debug("control ROUTER Channel on port: %i" % self.control_port)
|
||||
|
||||
self.init_iopub(context)
|
||||
|
||||
def init_iopub(self, context):
|
||||
self.iopub_socket = context.socket(zmq.PUB)
|
||||
self.iopub_socket.linger = 1000
|
||||
self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port)
|
||||
self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port)
|
||||
self.configure_tornado_logger()
|
||||
self.iopub_thread = IOPubThread(self.iopub_socket, pipe=True)
|
||||
self.iopub_thread.start()
|
||||
# backward-compat: wrap iopub socket API in background thread
|
||||
self.iopub_socket = self.iopub_thread.background_socket
|
||||
|
||||
def init_heartbeat(self):
|
||||
"""start the heart beating"""
|
||||
# heartbeat doesn't share context, because it mustn't be blocked
|
||||
# by the GIL, which is accessed by libzmq when freeing zero-copy messages
|
||||
hb_ctx = zmq.Context()
|
||||
self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port))
|
||||
self.hb_port = self.heartbeat.port
|
||||
self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port)
|
||||
self.heartbeat.start()
|
||||
|
||||
def log_connection_info(self):
|
||||
"""display connection info, and store ports"""
|
||||
basename = os.path.basename(self.connection_file)
|
||||
if basename == self.connection_file or \
|
||||
os.path.dirname(self.connection_file) == self.connection_dir:
|
||||
# use shortname
|
||||
tail = basename
|
||||
else:
|
||||
tail = self.connection_file
|
||||
lines = [
|
||||
"To connect another client to this kernel, use:",
|
||||
" --existing %s" % tail,
|
||||
]
|
||||
# log connection info
|
||||
# info-level, so often not shown.
|
||||
# frontends should use the %connect_info magic
|
||||
# to see the connection info
|
||||
for line in lines:
|
||||
self.log.info(line)
|
||||
# also raw print to the terminal if no parent_handle (`ipython kernel`)
|
||||
# unless log-level is CRITICAL (--quiet)
|
||||
if not self.parent_handle and self.log_level < logging.CRITICAL:
|
||||
io.rprint(_ctrl_c_message)
|
||||
for line in lines:
|
||||
io.rprint(line)
|
||||
|
||||
self.ports = dict(shell=self.shell_port, iopub=self.iopub_port,
|
||||
stdin=self.stdin_port, hb=self.hb_port,
|
||||
control=self.control_port)
|
||||
|
||||
def init_blackhole(self):
|
||||
"""redirects stdout/stderr to devnull if necessary"""
|
||||
if self.no_stdout or self.no_stderr:
|
||||
blackhole = open(os.devnull, 'w')
|
||||
if self.no_stdout:
|
||||
sys.stdout = sys.__stdout__ = blackhole
|
||||
if self.no_stderr:
|
||||
sys.stderr = sys.__stderr__ = blackhole
|
||||
|
||||
def init_io(self):
|
||||
"""Redirect input streams and set a display hook."""
|
||||
if self.outstream_class:
|
||||
outstream_factory = import_item(str(self.outstream_class))
|
||||
sys.stdout = outstream_factory(self.session, self.iopub_thread, u'stdout')
|
||||
sys.stderr = outstream_factory(self.session, self.iopub_thread, u'stderr')
|
||||
if self.displayhook_class:
|
||||
displayhook_factory = import_item(str(self.displayhook_class))
|
||||
self.displayhook = displayhook_factory(self.session, self.iopub_socket)
|
||||
sys.displayhook = self.displayhook
|
||||
|
||||
self.patch_io()
|
||||
|
||||
def patch_io(self):
|
||||
"""Patch important libraries that can't handle sys.stdout forwarding"""
|
||||
try:
|
||||
import faulthandler
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
# Warning: this is a monkeypatch of `faulthandler.enable`, watch for possible
|
||||
# updates to the upstream API and update accordingly (up-to-date as of Python 3.5):
|
||||
# https://docs.python.org/3/library/faulthandler.html#faulthandler.enable
|
||||
|
||||
# change default file to __stderr__ from forwarded stderr
|
||||
faulthandler_enable = faulthandler.enable
|
||||
def enable(file=sys.__stderr__, all_threads=True, **kwargs):
|
||||
return faulthandler_enable(file=file, all_threads=all_threads, **kwargs)
|
||||
|
||||
faulthandler.enable = enable
|
||||
|
||||
if hasattr(faulthandler, 'register'):
|
||||
faulthandler_register = faulthandler.register
|
||||
def register(signum, file=sys.__stderr__, all_threads=True, chain=False, **kwargs):
|
||||
return faulthandler_register(signum, file=file, all_threads=all_threads,
|
||||
chain=chain, **kwargs)
|
||||
faulthandler.register = register
|
||||
|
||||
def init_signal(self):
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
|
||||
def init_kernel(self):
|
||||
"""Create the Kernel object itself"""
|
||||
shell_stream = ZMQStream(self.shell_socket)
|
||||
control_stream = ZMQStream(self.control_socket)
|
||||
|
||||
kernel_factory = self.kernel_class.instance
|
||||
|
||||
kernel = kernel_factory(parent=self, session=self.session,
|
||||
shell_streams=[shell_stream, control_stream],
|
||||
iopub_thread=self.iopub_thread,
|
||||
iopub_socket=self.iopub_socket,
|
||||
stdin_socket=self.stdin_socket,
|
||||
log=self.log,
|
||||
profile_dir=self.profile_dir,
|
||||
user_ns=self.user_ns,
|
||||
)
|
||||
kernel.record_ports({
|
||||
name + '_port': port for name, port in self.ports.items()
|
||||
})
|
||||
self.kernel = kernel
|
||||
|
||||
# Allow the displayhook to get the execution count
|
||||
self.displayhook.get_execution_count = lambda: kernel.execution_count
|
||||
|
||||
def init_gui_pylab(self):
|
||||
"""Enable GUI event loop integration, taking pylab into account."""
|
||||
|
||||
# Register inline backend as default
|
||||
# this is higher priority than matplotlibrc,
|
||||
# but lower priority than anything else (mpl.use() for instance).
|
||||
# This only affects matplotlib >= 1.5
|
||||
if not os.environ.get('MPLBACKEND'):
|
||||
os.environ['MPLBACKEND'] = 'module://ipykernel.pylab.backend_inline'
|
||||
|
||||
# Provide a wrapper for :meth:`YAPInteractiveShellApp.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
|
||||
# is not associated with any execute request.
|
||||
|
||||
shell = self.shell
|
||||
_showtraceback = shell._showtraceback
|
||||
try:
|
||||
# replace error-sending traceback with stderr
|
||||
def print_tb(etype, evalue, stb):
|
||||
print ("GUI event loop or pylab initialization failed",
|
||||
file=sys.stderr)
|
||||
print (shell.InteractiveTB.stb2text(stb), file=sys.stderr)
|
||||
shell._showtraceback = print_tb
|
||||
InteractiveShellApp.init_gui_pylab(self)
|
||||
finally:
|
||||
shell._showtraceback = _showtraceback
|
||||
|
||||
def init_shell(self):
|
||||
self.shell = getattr(self.kernel, 'shell', None)
|
||||
if self.shell:
|
||||
self.shell.configurables.append(self)
|
||||
|
||||
def init_extensions(self):
|
||||
super(YAPKernelApp, self).init_extensions()
|
||||
# BEGIN HARDCODED WIDGETS HACK
|
||||
# Ensure ipywidgets extension is loaded if available
|
||||
extension_man = self.shell.extension_manager
|
||||
if 'ipywidgets' not in extension_man.loaded:
|
||||
try:
|
||||
extension_man.load_extension('ipywidgets')
|
||||
except ImportError as e:
|
||||
self.log.debug('ipywidgets package not installed. Widgets will not be available.')
|
||||
# END HARDCODED WIDGETS HACK
|
||||
|
||||
def configure_tornado_logger(self):
|
||||
""" Configure the tornado logging.Logger.
|
||||
|
||||
Must set up the tornado logger or else tornado will call
|
||||
basicConfig for the root logger which makes the root logger
|
||||
go to the real sys.stderr instead of the capture streams.
|
||||
This function mimics the setup of logging.basicConfig.
|
||||
"""
|
||||
logger = logging.getLogger('tornado')
|
||||
handler = logging.StreamHandler()
|
||||
formatter = logging.Formatter(logging.BASIC_FORMAT)
|
||||
handler.setFormatter(formatter)
|
||||
logger.addHandler(handler)
|
||||
|
||||
@catch_config_error
|
||||
def initialize(self, argv=None):
|
||||
super(YAPKernelApp, self).initialize(argv)
|
||||
if self.subapp is not None:
|
||||
return
|
||||
# register zmq IOLoop with tornado
|
||||
zmq_ioloop.install()
|
||||
self.init_blackhole()
|
||||
self.init_connection_file()
|
||||
self.init_poller()
|
||||
self.init_sockets()
|
||||
self.init_heartbeat()
|
||||
# writing/displaying connection info must be *after* init_sockets/heartbeat
|
||||
self.write_connection_file()
|
||||
# Log connection info after writing connection file, so that the connection
|
||||
# file is definitely available at the time someone reads the log.
|
||||
self.log_connection_info()
|
||||
self.init_io()
|
||||
self.init_signal()
|
||||
self.init_kernel()
|
||||
# shell init steps
|
||||
self.init_path()
|
||||
self.init_shell()
|
||||
if self.shell:
|
||||
self.init_gui_pylab()
|
||||
self.init_extensions()
|
||||
self.init_code()
|
||||
# flush stdout/stderr, so that anything written to these streams during
|
||||
# initialization do not get associated with the first execution request
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
|
||||
def start(self):
|
||||
if self.subapp is not None:
|
||||
return self.subapp.start()
|
||||
if self.poller is not None:
|
||||
self.poller.start()
|
||||
self.kernel.start()
|
||||
try:
|
||||
ioloop.IOLoop.instance().start()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
|
||||
launch_new_instance = YAPKernelApp.launch_instance
|
||||
|
||||
def main():
|
||||
"""Run an YAPKernel as an application"""
|
||||
app = YAPKernelApp.instance()
|
||||
app.initialize()
|
||||
app.start()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
@ -1,188 +0,0 @@
|
||||
"""The IPython kernel spec for Jupyter"""
|
||||
|
||||
# Copyright (c) IPython Development Team.
|
||||
# Distributed under the terms of the Modified BSD License.
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from jupyter_client.kernelspec import KernelSpecManager
|
||||
|
||||
pjoin = os.path.join
|
||||
|
||||
KERNEL_NAME = 'YAPKernel'
|
||||
|
||||
# path to kernelspec resources
|
||||
RESOURCES = pjoin(os.path.dirname(__file__), 'resources')
|
||||
|
||||
|
||||
def make_yap_kernel_cmd(mod='yap_kernel', executable=None, extra_arguments=None, **kw):
|
||||
"""Build Popen command list for launching an IPython kernel.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
mod : str, optional (default 'yap_kernel')
|
||||
A string of an IPython module whose __main__ starts an IPython kernel
|
||||
|
||||
executable : str, optional (default sys.executable)
|
||||
The Python executable to use for the kernel process.
|
||||
|
||||
extra_arguments : list, optional
|
||||
A list of extra arguments to pass when executing the launch code.
|
||||
|
||||
Returns
|
||||
-------
|
||||
|
||||
A Popen command list
|
||||
"""
|
||||
if executable is None:
|
||||
executable = sys.executable
|
||||
extra_arguments = extra_arguments or []
|
||||
arguments = [executable, '-m', mod, '-f', '{connection_file}']
|
||||
arguments.extend(extra_arguments)
|
||||
|
||||
return arguments
|
||||
|
||||
|
||||
def get_kernel_dict(extra_arguments={'mod':'yap_kernel'}):
|
||||
"""Construct dict for kernel.json"""
|
||||
return {
|
||||
'argv': make_yap_kernel_cmd(extra_arguments=extra_arguments),
|
||||
'display_name': 'YAPKernel 6',
|
||||
'language': 'prolog',
|
||||
}
|
||||
|
||||
|
||||
def write_kernel_spec(path=None, overrides=None, extra_arguments=None):
|
||||
"""Write a kernel spec directory to `path`
|
||||
|
||||
If `path` is not specified, a temporary directory is created.
|
||||
If `overrides` is given, the kernelspec JSON is updated before writing.
|
||||
|
||||
The path to the kernelspec is always returned.
|
||||
"""
|
||||
if path is None:
|
||||
path = os.path.join(tempfile.mkdtemp(suffix='_kernels'), KERNEL_NAME)
|
||||
|
||||
# stage resources
|
||||
shutil.copytree(RESOURCES, path)
|
||||
# write kernel.json
|
||||
kernel_dict = get_kernel_dict(extra_arguments)
|
||||
|
||||
if overrides:
|
||||
kernel_dict.update(overrides)
|
||||
with open(pjoin(path, 'kernel.json'), 'w') as f:
|
||||
json.dump(kernel_dict, f, indent=1)
|
||||
|
||||
return path
|
||||
|
||||
|
||||
def install(kernel_spec_manager=None, user=False, kernel_name=KERNEL_NAME, display_name=None,
|
||||
prefix=None, profile=None):
|
||||
"""Install the IPython kernelspec for Jupyter
|
||||
|
||||
Parameters
|
||||
----------
|
||||
|
||||
kernel_spec_manager: KernelSpecManager [optional]
|
||||
A KernelSpecManager to use for installation.
|
||||
If none provided, a default instance will be created.
|
||||
user: bool [default: False]
|
||||
Whether to do a user-only install, or system-wide.
|
||||
kernel_name: str, optional
|
||||
Specify a name for the kernelspec.
|
||||
This is needed for having multiple IPython kernels for different environments.
|
||||
display_name: str, optional
|
||||
Specify the display name for the kernelspec
|
||||
profile: str, optional
|
||||
Specify a custom profile to be loaded by the kernel.
|
||||
prefix: str, optional
|
||||
Specify an install prefix for the kernelspec.
|
||||
This is needed to install into a non-default location, such as a conda/virtual-env.
|
||||
|
||||
Returns
|
||||
-------
|
||||
|
||||
The path where the kernelspec was installed.
|
||||
"""
|
||||
if kernel_spec_manager is None:
|
||||
kernel_spec_manager = KernelSpecManager()
|
||||
|
||||
if (kernel_name != KERNEL_NAME) and (display_name is None):
|
||||
# kernel_name is specified and display_name is not
|
||||
# default display_name to kernel_name
|
||||
display_name = kernel_name
|
||||
overrides = {}
|
||||
if display_name:
|
||||
overrides["display_name"] = display_name
|
||||
if profile:
|
||||
extra_arguments = ["--profile", profile]
|
||||
if not display_name:
|
||||
# add the profile to the default display name
|
||||
overrides["display_name"] = 'Python %i [profile=%s]' % (sys.version_info[0], profile)
|
||||
else:
|
||||
extra_arguments = None
|
||||
path = write_kernel_spec(overrides=overrides, extra_arguments=extra_arguments)
|
||||
dest = kernel_spec_manager.install_kernel_spec(
|
||||
path, kernel_name=kernel_name, user=user, prefix=prefix)
|
||||
# cleanup afterward
|
||||
shutil.rmtree(path)
|
||||
return dest
|
||||
|
||||
# Entrypoint
|
||||
|
||||
from traitlets.config import Application
|
||||
|
||||
|
||||
class InstallIPythonKernelSpecApp(Application):
|
||||
"""Dummy app wrapping argparse"""
|
||||
name = 'ipython-kernel-install'
|
||||
|
||||
def initialize(self, argv=None):
|
||||
if argv is None:
|
||||
argv = sys.argv[1:]
|
||||
self.argv = argv
|
||||
|
||||
def start(self):
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(prog=self.name,
|
||||
description="Install the IPython 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.")
|
||||
parser.add_argument('--display-name', type=str,
|
||||
help="Specify the display name for the kernelspec."
|
||||
" This is helpful when you have multiple IPython kernels.")
|
||||
parser.add_argument('--profile', type=str,
|
||||
help="Specify an IPython profile to load. "
|
||||
"This can be used to create custom versions of the kernel.")
|
||||
parser.add_argument('--prefix', type=str,
|
||||
help="Specify an install prefix for the kernelspec."
|
||||
" This is needed to install into a non-default location, such as a conda/virtual-env.")
|
||||
parser.add_argument('--sys-prefix', action='store_const', const=sys.prefix, dest='prefix',
|
||||
help="Install to Python's sys.prefix."
|
||||
" Shorthand for --prefix='%s'. For use in conda/virtual-envs." % sys.prefix)
|
||||
opts = parser.parse_args(self.argv)
|
||||
try:
|
||||
dest = install(user=opts.user, kernel_name=opts.name, profile=opts.profile,
|
||||
prefix=opts.prefix, display_name=opts.display_name)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EACCES:
|
||||
print(e, file=sys.stderr)
|
||||
if opts.user:
|
||||
print("Perhaps you want `sudo` or `--user`?", file=sys.stderr)
|
||||
self.exit(1)
|
||||
raise
|
||||
print("Installed kernelspec %s in %s" % (opts.name, dest))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
InstallIPythonKernelSpecApp.launch_instance()
|
@ -56,7 +56,7 @@ setup_args = dict(
|
||||
version = version_ns['__version__'],
|
||||
scripts = glob(pjoin('scripts', '*')),
|
||||
packages = packages,
|
||||
py_modules = ['yapkernel_launcher'],
|
||||
py_modules = ['yap_kernel_launcher'],
|
||||
package_data = package_data,
|
||||
description = "YAP Kernel for Jupyter",
|
||||
author = 'YAP Development Team',
|
||||
|
@ -1,20 +0,0 @@
|
||||
Metadata-Version: 1.1
|
||||
Name: yap-kernel
|
||||
Version: 4.7.0.dev0
|
||||
Summary: YAP Kernel for Jupyter
|
||||
Home-page: http://ipython.org
|
||||
Author: YAP Development Team
|
||||
Author-email: ipython-dev@scipy.org
|
||||
License: BSD
|
||||
Description: UNKNOWN
|
||||
Keywords: Interactive,Interpreter,Shell,Web
|
||||
Platform: Linux
|
||||
Platform: Mac OS X
|
||||
Platform: Windows
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Intended Audience :: System Administrators
|
||||
Classifier: Intended Audience :: Science/Research
|
||||
Classifier: License :: OSI Approved :: BSD License
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
@ -1,81 +0,0 @@
|
||||
CONTRIBUTING.md
|
||||
COPYING.md
|
||||
MANIFEST.in
|
||||
README.md
|
||||
setup.cfg
|
||||
setup.py
|
||||
/Users/vsc/github/yap-6.3/yap_kernel/data_kernelspec/kernel.json
|
||||
/Users/vsc/github/yap-6.3/yap_kernel/data_kernelspec/logo-32x32.png
|
||||
/Users/vsc/github/yap-6.3/yap_kernel/data_kernelspec/logo-64x64.png
|
||||
docs/Makefile
|
||||
docs/changelog.rst
|
||||
docs/conf.py
|
||||
docs/index.rst
|
||||
docs/make.bat
|
||||
examples/embedding/inprocess_qtconsole.py
|
||||
examples/embedding/inprocess_terminal.py
|
||||
examples/embedding/internal_ipkernel.py
|
||||
examples/embedding/ipkernel_qtapp.py
|
||||
examples/embedding/ipkernel_wxapp.py
|
||||
yap_kernel/__init__.py
|
||||
yap_kernel/__main__.py
|
||||
yap_kernel/_version.py
|
||||
yap_kernel/codeutil.py
|
||||
yap_kernel/connect.py
|
||||
yap_kernel/datapub.py
|
||||
yap_kernel/displayhook.py
|
||||
yap_kernel/embed.py
|
||||
yap_kernel/eventloops.py
|
||||
yap_kernel/heartbeat.py
|
||||
yap_kernel/interactiveshell.py
|
||||
yap_kernel/iostream.py
|
||||
yap_kernel/jsonutil.py
|
||||
yap_kernel/kernelapp.py
|
||||
yap_kernel/kernelbase.py
|
||||
yap_kernel/kernelspec.py
|
||||
yap_kernel/log.py
|
||||
yap_kernel/parentpoller.py
|
||||
yap_kernel/pickleutil.py
|
||||
yap_kernel/serialize.py
|
||||
yap_kernel/yapkernel.py
|
||||
yap_kernel/zmqshell.py
|
||||
yap_kernel.egg-info/PKG-INFO
|
||||
yap_kernel.egg-info/SOURCES.txt
|
||||
yap_kernel.egg-info/dependency_links.txt
|
||||
yap_kernel.egg-info/requires.txt
|
||||
yap_kernel.egg-info/top_level.txt
|
||||
yap_kernel/comm/__init__.py
|
||||
yap_kernel/comm/comm.py
|
||||
yap_kernel/comm/manager.py
|
||||
yap_kernel/gui/__init__.py
|
||||
yap_kernel/gui/gtk3embed.py
|
||||
yap_kernel/gui/gtkembed.py
|
||||
yap_kernel/inprocess/__init__.py
|
||||
yap_kernel/inprocess/blocking.py
|
||||
yap_kernel/inprocess/channels.py
|
||||
yap_kernel/inprocess/client.py
|
||||
yap_kernel/inprocess/constants.py
|
||||
yap_kernel/inprocess/ipkernel.py
|
||||
yap_kernel/inprocess/manager.py
|
||||
yap_kernel/inprocess/socket.py
|
||||
yap_kernel/inprocess/tests/__init__.py
|
||||
yap_kernel/inprocess/tests/test_kernel.py
|
||||
yap_kernel/inprocess/tests/test_kernelmanager.py
|
||||
yap_kernel/pylab/__init__.py
|
||||
yap_kernel/pylab/backend_inline.py
|
||||
yap_kernel/pylab/config.py
|
||||
yap_kernel/resources/logo-32x32.png
|
||||
yap_kernel/resources/logo-64x64.png
|
||||
yap_kernel/tests/__init__.py
|
||||
yap_kernel/tests/test_connect.py
|
||||
yap_kernel/tests/test_embed_kernel.py
|
||||
yap_kernel/tests/test_io.py
|
||||
yap_kernel/tests/test_jsonutil.py
|
||||
yap_kernel/tests/test_kernel.py
|
||||
yap_kernel/tests/test_kernelspec.py
|
||||
yap_kernel/tests/test_message_spec.py
|
||||
yap_kernel/tests/test_pickleutil.py
|
||||
yap_kernel/tests/test_serialize.py
|
||||
yap_kernel/tests/test_start_kernel.py
|
||||
yap_kernel/tests/test_zmq_shell.py
|
||||
yap_kernel/tests/utils.py
|
@ -1,12 +0,0 @@
|
||||
ipython>=4.0.0
|
||||
traitlets>=4.1.0
|
||||
jupyter_client
|
||||
tornado>=4.0
|
||||
yap4py
|
||||
|
||||
[test]
|
||||
nose_warnings_filters
|
||||
nose-timer
|
||||
|
||||
[test:python_version=="2.7"]
|
||||
mock
|
@ -1,2 +0,0 @@
|
||||
yap_kernel
|
||||
yapkernel_launcher
|
Reference in New Issue
Block a user