use of org.python.core.PyJavaType in project gda-core by openGDA.
the class GDAInteractiveConsole method showexception.
/**
* Show syntax error messages in the Terminal This is to work around an apparent bug in jython. showexception will
* print to the terminal for ordinary stuff, just not PySyntaxErrors.
* log as error as it is an exception
* Only show cause as a single line on teh Jython console
*/
@Override
public void showexception(PyException arg0) {
if (arg0.match(Py.SyntaxError) || arg0.match(Py.IndentationError)) {
if (logger.isTraceEnabled())
super.showexception(arg0);
InterfaceProvider.getTerminalPrinter().print(arg0.toString());
} else if (arg0.match(Py.KeyboardInterrupt)) {
InterfaceProvider.getTerminalPrinter().print("KeyboardInterrupt");
} else if (arg0.match(Py.SystemExit)) {
// super.showexception handles SystemExit as a special case and shuts down the JVM
blockExit();
} else {
InterfaceProvider.getTerminalPrinter().print("Error time: " + Instant.now());
if (arg0.type instanceof PyJavaType) {
// we cut it down to the jython stack trace and the exception message (and class)
if (arg0.traceback != null) {
// Occasionally exceptions have no traceback - see DAQ-3628
InterfaceProvider.getTerminalPrinter().print(arg0.traceback.dumpStack());
}
PyObject value = arg0.value;
Throwable throwable = (Throwable) value.__tojava__(Throwable.class);
InterfaceProvider.getTerminalPrinter().print(throwable.getClass().getName() + ": " + throwable.getMessage());
} else {
super.showexception(arg0);
}
}
// always log as error. It is up to the log config to decide how much of the exception is to be shown
// If a PyException getMessage returns null. toString returns the stack which is not what we want as we pass the whole stack in the throwable to the
// error method
// Sometimes the cause is null
String msg;
if (arg0.getMessage() == null) {
if (arg0.getCause() == null)
msg = arg0.toString();
else
msg = arg0.getCause().getMessage();
} else
msg = arg0.getMessage();
if (arg0.getCause() instanceof ScanInterruptedException) {
logger.info("InteractiveConsole exception: " + msg);
} else {
logger.error("InteractiveConsole exception: " + msg, arg0);
}
}
use of org.python.core.PyJavaType in project Pydev by fabioz.
the class JythonPlugin method exec.
/**
* @param pythonpathFolders folders that should be in the pythonpath when executing the script
* @see JythonPlugin#exec(HashMap, String, PythonInterpreter)
* Same as before but the file to execute is passed as a parameter
*/
public static Throwable exec(HashMap<String, Object> locals, IPythonInterpreter interpreter, File fileToExec, File[] pythonpathFolders, String... argv) {
if (locals == null) {
locals = new HashMap<String, Object>();
}
if (interpreter == null) {
// already disposed
return null;
}
locals.put("__file__", fileToExec.toString());
try {
String codeObjName;
synchronized (codeCache) {
// hold on there... one at a time... please?
String fileName = fileToExec.getName();
if (!fileName.endsWith(".py")) {
throw new RuntimeException("The script to be executed must be a python file. Name:" + fileName);
}
codeObjName = "code" + fileName.substring(0, fileName.indexOf('.'));
final String codeObjTimestampName = codeObjName + "Timestamp";
for (Map.Entry<String, Object> entry : locals.entrySet()) {
interpreter.set(entry.getKey(), entry.getValue());
}
boolean regenerate = false;
if (interpreter instanceof PythonInterpreterWrapperNotShared) {
// Always regenerate if the state is not shared! (otherwise the pythonpath might be wrong as the sys is not the same)
regenerate = true;
}
Tuple<Long, Object> timestamp = codeCache.get(fileToExec);
final long lastModified = FileUtils.lastModified(fileToExec);
if (timestamp == null || timestamp.o1 != lastModified) {
// the file timestamp changed, so, we have to regenerate it
regenerate = true;
}
if (!regenerate) {
// if the 'code' object does not exist or if it's timestamp is outdated, we have to re-set it.
PyObject obj = (PyObject) interpreter.get(codeObjName);
PyObject pyTime = (PyObject) interpreter.get(codeObjTimestampName);
if (obj == null || pyTime == null || !pyTime.__tojava__(Long.class).equals(timestamp.o1)) {
if (DEBUG) {
System.out.println("Resetting object: " + codeObjName);
}
interpreter.set(codeObjName, timestamp.o2);
interpreter.set(codeObjTimestampName, timestamp.o1);
}
}
if (regenerate) {
if (DEBUG) {
System.out.println("Regenerating: " + codeObjName);
}
String path = FileUtils.getFileAbsolutePath(fileToExec);
StringBuffer strPythonPathFolders = new StringBuffer();
strPythonPathFolders.append("[");
for (File file : pythonpathFolders) {
if (file != null) {
strPythonPathFolders.append("r'");
strPythonPathFolders.append(FileUtils.getFileAbsolutePath(file));
strPythonPathFolders.append("',");
}
}
strPythonPathFolders.append("]");
StringBuffer addToSysPath = new StringBuffer();
// we will only add the paths to the pythonpath if it was still not set or if it changed (but it will never remove the ones added before).
// we have to put that in sys because it is the same across different interpreters
addToSysPath.append("if not hasattr(sys, 'PYDEV_PYTHONPATH_SET') or sys.PYDEV_PYTHONPATH_SET != ");
addToSysPath.append(strPythonPathFolders);
addToSysPath.append(":\n");
addToSysPath.append(" sys.PYDEV_PYTHONPATH_SET = ");
addToSysPath.append(strPythonPathFolders);
addToSysPath.append("\n");
addToSysPath.append(" sys.path += ");
addToSysPath.append(strPythonPathFolders);
addToSysPath.append("\n");
if (argv.length > 0) {
addToSysPath.append("sys.argv = [");
for (String s : argv) {
addToSysPath.append(s);
addToSysPath.append(",");
}
addToSysPath.append("];");
addToSysPath.append("\n");
}
String toExec = StringUtils.format(LOAD_FILE_SCRIPT, path, path, addToSysPath.toString());
interpreter.exec(toExec);
String exec = StringUtils.format("%s = compile(toExec, r'%s', 'exec')", codeObjName, path);
interpreter.exec(exec);
// set its timestamp
interpreter.set(codeObjTimestampName, lastModified);
Object codeObj = interpreter.get(codeObjName);
codeCache.put(fileToExec, new Tuple<Long, Object>(lastModified, codeObj));
}
}
interpreter.exec(StringUtils.format("exec(%s)", codeObjName));
} catch (Throwable e) {
if (!IN_TESTS && JythonPlugin.getDefault() == null) {
// it is already disposed
return null;
}
// the user requested it to exit
if (e instanceof ExitScriptException) {
return null;
}
// actually, this is more likely to happen when raising an exception in jython
if (e instanceof PyException) {
PyException pE = (PyException) e;
if (pE.type instanceof PyJavaType) {
PyJavaType t = (PyJavaType) pE.type;
if (t.getName() != null && t.getName().indexOf("ExitScriptException") != -1) {
return null;
}
} else if (pE.type instanceof PyClass) {
PyClass t = (PyClass) pE.type;
if (t.__name__ != null && t.__name__.equals("SystemExit")) {
return null;
}
}
}
if (JyScriptingPreferencesPage.getShowScriptingOutput()) {
Log.log(IStatus.ERROR, "Error while executing:" + fileToExec, e);
}
return e;
}
return null;
}
use of org.python.core.PyJavaType in project sponge by softelnet.
the class JythonKnowledgeBaseInterpreter method scanToAutoEnable.
@Override
public void scanToAutoEnable() {
PyScriptEngineScope scope = eval("globals()");
List<PyType> processorPyTypes = getProcessorClasses().values().stream().map(cls -> (PyType) Py.java2py(cls)).collect(Collectors.toList());
List<Object> autoEnabled = new ArrayList<>();
SpongeUtils.stream(((ScopeIterator) scope.__iter__()).iterator()).forEachOrdered(element -> {
String name = element.toString();
PyObject pyObject = scope.__finditem__(name);
// Java-based processor classes (extending PyJavaType) are not auto-enabled.
if (pyObject != null && pyObject instanceof PyType && !(pyObject instanceof PyJavaType)) {
PyType pyType = (PyType) pyObject;
boolean extendsProcessorType = processorPyTypes.stream().filter(processorClass -> !pyType.equals(processorClass) && pyType.isSubType(processorClass)).findFirst().isPresent();
if (extendsProcessorType && !isProcessorAbstract(name)) {
autoEnabled.add(name);
((JythonKnowledgeBaseEngineOperations) getEngineOperations()).enable(pyType);
}
}
});
if (logger.isDebugEnabled() && !autoEnabled.isEmpty()) {
logger.debug("Auto-enabling: {}", autoEnabled);
}
}
Aggregations