Search in sources :

Example 1 with PyJavaType

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);
    }
}
Also used : PyString(org.python.core.PyString) PyObject(org.python.core.PyObject) PyJavaType(org.python.core.PyJavaType) ScanInterruptedException(gda.scan.ScanInterruptedException)

Example 2 with PyJavaType

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;
}
Also used : PyClass(org.python.core.PyClass) PyException(org.python.core.PyException) PyObject(org.python.core.PyObject) HashMap(java.util.HashMap) Map(java.util.Map) PyObject(org.python.core.PyObject) File(java.io.File) PyJavaType(org.python.core.PyJavaType)

Example 3 with PyJavaType

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);
    }
}
Also used : Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) KnowledgeBase(org.openksavi.sponge.kb.KnowledgeBase) ActionBuilder(org.openksavi.sponge.action.ActionBuilder) StringUtils(org.apache.commons.lang3.StringUtils) BaseSpongeEngine(org.openksavi.sponge.core.engine.BaseSpongeEngine) SpongeEngine(org.openksavi.sponge.engine.SpongeEngine) ArrayList(java.util.ArrayList) EngineScriptKnowledgeBaseInterpreter(org.openksavi.sponge.core.kb.EngineScriptKnowledgeBaseInterpreter) JythonOutputStreamValue(org.openksavi.sponge.jython.JythonOutputStreamValue) ScopeIterator(org.python.jsr223.PyScriptEngineScope.ScopeIterator) PySystemState(org.python.core.PySystemState) PyScriptEngineScope(org.python.jsr223.PyScriptEngineScope) PythonConstants(org.openksavi.sponge.jython.PythonConstants) OutputStreamValue(org.openksavi.sponge.type.value.OutputStreamValue) Compilable(javax.script.Compilable) PyPredicate(org.openksavi.sponge.jython.util.PyPredicate) Logger(org.slf4j.Logger) JythonActionBuilder(org.openksavi.sponge.jython.JythonActionBuilder) JythonRule(org.openksavi.sponge.jython.JythonRule) Plugin(org.openksavi.sponge.plugin.Plugin) PyBiConsumer(org.openksavi.sponge.jython.util.PyBiConsumer) ScriptEngineManager(javax.script.ScriptEngineManager) PyObject(org.python.core.PyObject) Reader(java.io.Reader) PySupplier(org.openksavi.sponge.jython.util.PySupplier) Collectors(java.util.stream.Collectors) Py(org.python.core.Py) KnowledgeBaseConstants(org.openksavi.sponge.kb.KnowledgeBaseConstants) List(java.util.List) Validate(org.apache.commons.lang3.Validate) Invocable(javax.script.Invocable) JythonUtils(org.openksavi.sponge.jython.util.JythonUtils) BasePlugin(org.openksavi.sponge.core.plugin.BasePlugin) ScriptKnowledgeBaseInterpreter(org.openksavi.sponge.kb.ScriptKnowledgeBaseInterpreter) PyType(org.python.core.PyType) PyConsumer(org.openksavi.sponge.jython.util.PyConsumer) PyJavaType(org.python.core.PyJavaType) SpongeException(org.openksavi.sponge.SpongeException) ScriptEngine(javax.script.ScriptEngine) Rule(org.openksavi.sponge.rule.Rule) SpongeUtils(org.openksavi.sponge.core.util.SpongeUtils) Collections(java.util.Collections) ArrayList(java.util.ArrayList) ScopeIterator(org.python.jsr223.PyScriptEngineScope.ScopeIterator) PyScriptEngineScope(org.python.jsr223.PyScriptEngineScope) PyType(org.python.core.PyType) PyObject(org.python.core.PyObject) PyObject(org.python.core.PyObject) PyJavaType(org.python.core.PyJavaType)

Aggregations

PyJavaType (org.python.core.PyJavaType)3 PyObject (org.python.core.PyObject)3 ScanInterruptedException (gda.scan.ScanInterruptedException)1 File (java.io.File)1 Reader (java.io.Reader)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1 Compilable (javax.script.Compilable)1 Invocable (javax.script.Invocable)1 ScriptEngine (javax.script.ScriptEngine)1 ScriptEngineManager (javax.script.ScriptEngineManager)1 StringUtils (org.apache.commons.lang3.StringUtils)1 Validate (org.apache.commons.lang3.Validate)1 SpongeException (org.openksavi.sponge.SpongeException)1 ActionBuilder (org.openksavi.sponge.action.ActionBuilder)1