org.python.core.Py Java Examples

The following examples show how to use org.python.core.Py. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JIntrospect.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Complete package name
 *
 * @param target Target
 * @return Package names
 */
public List<String> completePackageName(String target) {
    String[] targetComponents = target.split("\\.");
    String base = targetComponents[0];
    PySystemState state = interp.getSystemState();
    PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__"));
    PyObject module = importer.__call__(Py.newString(base));
    if (targetComponents.length > 1) {
        for (int i = 1; i < targetComponents.length; i++) {
            module = module.__getattr__(targetComponents[i]);
        }
    }
    PyList plist = (PyList) module.__dir__();
    List<String> list = new ArrayList<>();
    String name;
    for (int i = 0; i < plist.__len__(); i++) {
        name = plist.get(i).toString();
        if (!name.startsWith("__")) {
            list.add(name);
        }
    }
    //list.add("*");

    return list;
}
 
Example #2
Source File: PythonRunner.java    From mdw with Apache License 2.0 6 votes vote down vote up
private static synchronized ScriptEngine getScriptEngine() throws ScriptException {
    if (scriptEngine == null) {
        PySystemState engineSys = new PySystemState();
        String assetRoot = ApplicationContext.getAssetRoot().getAbsolutePath();
        engineSys.path.append(Py.newString(assetRoot));
        Py.setSystemState(engineSys);
        scriptEngine = new PyScriptEngineFactory().getScriptEngine();
        // custom module finder for assets
        String assetPath = "com.centurylink.mdw.python/ModuleFinder.py";
        try {
            Asset finderAsset = AssetCache.getAsset(assetPath);
            Map<String, Object> values = new HashMap<>();
            values.put("assetRoot", assetRoot);
            Bindings bindings = new SimpleBindings(values);
            ScriptContext scriptContext = new SimpleScriptContext();
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptEngine.eval(finderAsset.getText(), scriptContext);
        } catch (IOException ex) {
            throw new ScriptException(ex);
        }
    }
    return scriptEngine;
}
 
Example #3
Source File: ArgParser.java    From pycode-minecraft with MIT License 6 votes vote down vote up
public void parse(PyObject[] args, String[] kws) {
    int nargs = args.length - kws.length;
    
    if (nargs < fixedArgs.length) {
        // TODO I need to verify these exceptions bubble up correctly
        throw Py.TypeError(String.format("Not enough arguments to %s(): %d provided, %d needed",
                funcname, nargs, fixedArgs.length));
    }

    // fixed arguments
    for (int i=0; i < fixedArgs.length; i++) {
        this.args.put(fixedArgs[i], args[i]);
    }

    // keyword arguments
    for (int i=0; i < kws.length; i++) {
        if (!this.keywordArgs.contains(kws[i])) {
            throw Py.TypeError(String.format("Unexpected keyword argument to %s(): %s",
                    funcname, kws[i]));
        }
        this.args.put(kws[i], args[nargs + i]);
    }
}
 
Example #4
Source File: QueryableDevice.java    From androidtestdebug with MIT License 6 votes vote down vote up
/**
 * Get the coordinates of the element's center.
 * 
 * @param selector
 *            the element selector
 * @return the (x,y) coordinates of the center
 * @throws IOException
 * @throws UnsupportedEncodingException
 * @throws RecognitionException
 */
private Point getElementCenter(By selector, ControlHierarchy ch)
		throws UnsupportedEncodingException, IOException,
		RecognitionException {
	List<ITreeNode> result = selector.query(ch.getAllNodes());
	if (result == null) {
		throw new PyException(Py.ValueError, String.format(
				"找不到iQuery语句指定的控件: %s", selector.getSelector()));
	}

	if (result.size() != 1) {
		throw new PyException(Py.ValueError, String.format(
				"iQuery查询语句找到多于一个控件: %s", selector.getSelector()));
	}

	ITreeNode node = result.get(0);
	Point p = getAbsoluteCenterOfView(node);
	return p;
}
 
Example #5
Source File: JythonUtils.java    From spork with Apache License 2.0 6 votes vote down vote up
public static PyObject pigToPython(Object object) {
    if (object instanceof Tuple) {
        return pigTupleToPyTuple((Tuple) object);
    } else if (object instanceof DataBag) {
        PyList list = new PyList();
        for (Tuple bagTuple : (DataBag) object) {
            list.add(pigTupleToPyTuple(bagTuple));
        }
        return list;
    } else if (object instanceof Map<?, ?>) {
        PyDictionary newMap = new PyDictionary();
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
            newMap.put(entry.getKey(), pigToPython(entry.getValue()));
        }
        return newMap;
    } else if (object instanceof DataByteArray) {
        return Py.java2py(((DataByteArray) object).get());
    } else {
        return Py.java2py(object);
    }
}
 
Example #6
Source File: JythonScriptEngine.java    From spork with Apache License 2.0 6 votes vote down vote up
@Override
protected Map<String, Object> getParamsFromVariables() throws IOException {
    PyFrame frame = Py.getFrame();
    @SuppressWarnings("unchecked")
    List<PyTuple> locals = ((PyStringMap) frame.getLocals()).items();
    Map<String, Object> vars = new HashMap<String, Object>();
    for (PyTuple item : locals) {
        String key = (String) item.get(0);
        Object obj = item.get(1);
        if (obj != null) {
            String value = item.get(1).toString();
            vars.put(key, value);
        }
    }
    return vars;
}
 
Example #7
Source File: JythonUtils.java    From AndroidRobot with Apache License 2.0 6 votes vote down vote up
public static List<Object> getList(ArgParser ap, int position)
/*     */   {
/* 169 */     PyObject arg = ap.getPyObject(position, Py.None);
/* 170 */     if (Py.isInstance(arg, PyNone.TYPE)) {
/* 171 */       return Collections.emptyList();
/*     */     }
/*     */
/* 174 */     List ret = Lists.newArrayList();
/* 175 */     PyList array = (PyList)arg;
/* 176 */     for (int x = 0; x < array.__len__(); x++) {
/* 177 */       PyObject item = array.__getitem__(x);
/*     */
/* 179 */       Class javaClass = (Class)PYOBJECT_TO_JAVA_OBJECT_MAP.get(item.getClass());
/* 180 */       if (javaClass != null) {
/* 181 */         ret.add(item.__tojava__(javaClass));
/*     */       }
/*     */     }
/* 184 */     return ret;
/*     */   }
 
Example #8
Source File: JythonUtils.java    From AndroidRobot with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> getMap(ArgParser ap, int position)
/*     */   {
/* 196 */     PyObject arg = ap.getPyObject(position, Py.None);
/* 197 */     if (Py.isInstance(arg, PyNone.TYPE)) {
/* 198 */       return Collections.emptyMap();
/*     */     }
/*     */
/* 201 */     Map ret = Maps.newHashMap();
/*     */
/* 203 */     PyDictionary dict = (PyDictionary)arg;
/* 204 */     PyList items = dict.items();
/* 205 */     for (int x = 0; x < items.__len__(); x++)
/*     */     {
/* 207 */       PyTuple item = (PyTuple)items.__getitem__(x);
/*     */
/* 209 */       String key = (String)item.__getitem__(0).__str__().__tojava__(String.class);
/* 210 */       PyObject value = item.__getitem__(1);
/*     */
/* 213 */       Class javaClass = (Class)PYOBJECT_TO_JAVA_OBJECT_MAP.get(value.getClass());
/* 214 */       if (javaClass != null) {
/* 215 */         ret.put(key, value.__tojava__(javaClass));
/*     */       }
/*     */     }
/* 218 */     return ret;
/*     */   }
 
Example #9
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
public void propertyChange(PropertyChangeEvent e) {
 super.propertyChange(e);
 String name = e.getPropertyName();
    Object value = e.getNewValue();
    if (name.equals("classLoader")) {
Py.getSystemState().setClassLoader((ClassLoader) value);
    }

}
 
Example #10
Source File: AdapterMap.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Convert java object to its corresponding PyObject representation.
 *
 * @param o Java object
 * @return PyObject
 */
public static PyObject adapt(Object o) {
	if (o instanceof PyObject) {
		return (PyObject) o;
	}
	return Py.java2py(o);
}
 
Example #11
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
public Object unwrap(PyObject result) {
if (result != null) {
   Object ret = result.__tojava__(Object.class);
   if (ret != Py.NoConversion)
	  return ret;
}
return result;
 }
 
Example #12
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
 * call the named method of the given object.
 */
public Object call (Object object, String method, Object[] args) 
    throws BSFException {
    try {
        PyObject[] pyargs = Py.EmptyObjects;

        if (args != null) {
            pyargs = new PyObject[args.length];
            for (int i = 0; i < pyargs.length; i++)
                pyargs[i] = Py.java2py(args[i]);
        }

        if (object != null) {
            PyObject o = Py.java2py(object);
            return unwrap(o.invoke(method, pyargs));
        }

        PyObject m = interp.get(method);

        if (m == null)
            m = interp.eval(method);
        if (m != null) {
            return unwrap(m.__call__(pyargs));
        }

        return null;
    } catch (PyException e) {
        throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
                                "exception from Jython:\n" + e, e);
    }
}
 
Example #13
Source File: JyInterpreter.java    From minecraft-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void runcode(PyObject code) {
    try {
        exec(code);
    } catch (PyException exc) {
        if (exc.match(Py.SystemExit)) {
            // Suppress this: we don't want clients to stop the whole JVM!
        	// We do stop this interpreter, however
        	this.close();
        	return;
        }
        showexception(exc);
    }
}
 
Example #14
Source File: JyInterpreter.java    From minecraft-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void execfile(File script) {
	lastCall = System.currentTimeMillis();
	try {
		super.execfile(script.getAbsolutePath());
	} catch (PyException exc) {
           if (exc.match(Py.SystemExit)) {
               // Suppress this: we don't want clients to stop the whole JVM!
           	// We do stop this interpreter, however
           	this.close();
           	return;
           }
           showexception(exc);
       }
}
 
Example #15
Source File: JythonFunction.java    From spork with Apache License 2.0 5 votes vote down vote up
@Override
public Schema outputSchema(Schema input) {
    if(schema != null) {
        return schema;
    } else {
        if(outputSchemaFunc != null) {
            PyFunction pf;
            try {
                pf = JythonScriptEngine.getFunction(scriptFilePath, outputSchemaFunc);
                // this should be a schema function
                PyObject schemaFunctionDef = pf.__findattr__("schemaFunction".intern());
                if(schemaFunctionDef == null) {
                    throw new IllegalStateException("Function: "
                            + outputSchemaFunc + " is not a schema function");
                }
                Object newSchema = ((pf.__call__(Py.java2py(input))).__tojava__(Object.class));
                if (newSchema instanceof ResourceSchema) {
                    return(Schema.getPigSchema((ResourceSchema) newSchema));
                }
                else if (newSchema instanceof Schema) {
                    return (Schema) newSchema;
                }
                else {
                    return Utils.getSchemaFromString(newSchema.toString());
                }
            } catch (IOException ioe) {
                throw new IllegalStateException("Could not find function: "
                    + outputSchemaFunc + "()", ioe);
            }
        } else {
            return new Schema(new Schema.FieldSchema(null, DataType.BYTEARRAY));
        }
    }
}
 
Example #16
Source File: JythonUtils.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
private static PyObject convertObject(Object o) {
/* 222 */     if ((o instanceof String))
/* 223 */       return new PyString((String)o);
/* 224 */     if ((o instanceof Double))
/* 225 */       return new PyFloat(((Double)o).doubleValue());
/* 226 */     if ((o instanceof Integer))
/* 227 */       return new PyInteger(((Integer)o).intValue());
/* 228 */     if ((o instanceof Float)) {
/* 229 */       float f = ((Float)o).floatValue();
/* 230 */       return new PyFloat(f);
/*     */     }
/* 232 */     return Py.None;
/*     */   }
 
Example #17
Source File: JythonUtils.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public static double getFloat(ArgParser ap, int position, double defaultValue)
/*     */   {
/* 149 */     PyObject arg = ap.getPyObject(position, new PyFloat(defaultValue));
/*     */
/* 151 */     if (Py.isInstance(arg, PyFloat.TYPE)) {
/* 152 */       return ((PyFloat)arg).asDouble();
/*     */     }
/* 154 */     if (Py.isInstance(arg, PyInteger.TYPE)) {
/* 155 */       return ((PyInteger)arg).asDouble();
/*     */     }
/* 157 */     throw Py.TypeError("Unable to parse argument: " + position);
/*     */   }
 
Example #18
Source File: JythonUtils.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public static double getFloat(ArgParser ap, int position)
/*     */   {
/* 129 */     PyObject arg = ap.getPyObject(position);
/*     */
/* 131 */     if (Py.isInstance(arg, PyFloat.TYPE)) {
/* 132 */       return ((PyFloat)arg).asDouble();
/*     */     }
/* 134 */     if (Py.isInstance(arg, PyInteger.TYPE)) {
/* 135 */       return ((PyInteger)arg).asDouble();
/*     */     }
/* 137 */     throw Py.TypeError("Unable to parse argument: " + position);
/*     */   }
 
Example #19
Source File: RoofGen.java    From pycode-minecraft with MIT License 5 votes vote down vote up
public static void roof(ArgParser r, World world, BlockPos pos, EnumFacing facing) throws BlockTypeError {
    int aWidth = r.getInteger("width");
    int aDepth = r.getInteger("depth");
    if (aWidth < 2) {
        throw Py.TypeError("width must be > 1");
    }
    if (aDepth < 2) {
        throw Py.TypeError("depth must be > 1");
    }
    String style = r.getString("style", "hip");
    boolean box = false;
    if (style.startsWith("box-")) {
        box = true;
        style = style.substring(4);
    }

    RoofGen gen = new RoofGen((WorldServer) world, pos, facing,
            r.getString("blockname"), aWidth, aDepth, r);

    switch (style) {
        case "hip":
            gen.hip();
            break;
        case "gable":
            gen.gable(box);
            break;
        case "shed":
            gen.shed(box);
            break;
        default:
            throw Py.TypeError(String.format("unknown style '%s'", r.getString("style")));
    }
}
 
Example #20
Source File: ArgParser.java    From pycode-minecraft with MIT License 5 votes vote down vote up
private int asInt(PyObject value) {
    if(value instanceof PyFloat) {
        Py.warning(Py.DeprecationWarning, "integer argument expected, got float");
        value = value.__int__();
    }

    return value.asInt();
}
 
Example #21
Source File: ArgParser.java    From pycode-minecraft with MIT License 5 votes vote down vote up
public PyObject get(String name) {
    PyObject value = this.args.get(name);
    if(value == null) {
        throw Py.TypeError(String.format("Missing argument to %s(): %s",
                funcname, name));
    }
    return value;
}
 
Example #22
Source File: FrmConsole.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
     * Initialize console
     */
    public void InitializeConsole() {
        JConsole console = new JConsole();
        console.setLocale(Locale.getDefault());
        System.out.println(console.getFont());
        console.setPreferredSize(new Dimension(600, 400));
        console.println(new ImageIcon(this.getClass().getResource("/images/jython_small_c.png")));        

//        boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().
//                getInputArguments().toString().contains("jdwp");
        String pluginPath = this.frmMain.getStartupPath() + File.separator + "plugins";
        List<String> jarfns = GlobalUtil.getFiles(pluginPath, ".jar");

        Py.getSystemState().setdefaultencoding("utf-8");
        PythonInteractiveInterpreter interp = new PythonInteractiveInterpreter(console);

        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try {
            interp.exec("import sys");
            //interp.exec("sys.path.append('" + path + "')");
            //interp.exec("from milab import *");
            //interp.exec("mipylib.miplot.isinteractive = True");
            interp.set("miapp", frmMain);
            for (String jarfn : jarfns) {
                interp.exec("sys.path.append('" + jarfn + "')");
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.setCursor(Cursor.getDefaultCursor());
        }

        new Thread(interp).start();
        this.setCursor(Cursor.getDefaultCursor());
        JIntrospect nameComplete = new JIntrospect(interp);
        console.setNameCompletion(nameComplete);
        this.getContentPane().add(console, BorderLayout.CENTER);
    }
 
Example #23
Source File: JConsole.java    From opensim-gui with Apache License 2.0 4 votes vote down vote up
/**
     * 
     */
    public JConsole() {
        
        // create streams that will link with this
        in = new ConsoleInputStream(this);
        // System.setIn(in);
        out = new ConsoleOutputStream(this);
        //System.setOut(new PrintStream(out));
        err = new ConsoleOutputStream(this);
        // setup the command history
        history = new CommandHistory();
        // setup the script engine
//        interp = new InteractiveInterpreter();

        // no postProps, registry values used 
        JLineConsole.initialize(System.getProperties(), null, new String[0]);

        interp = new JLineConsole();
	
        // important line, set JLineConsole to internal python variable to be able to 
        // acces console from python interface
        interp.getSystemState().__setattr__("_jy_interpreter", Py.java2py(interp));
        interp.getSystemState().__setattr__("_jy_main", Py.java2py(this));
	
        // this instance - in order to call interrupt on correct thread

        // JLINE console initialization
//        JLineConsole.initialize(System.getProperties(), null, new String[0]);       // setup the script interp
        
        // enable autocomplete by default:)
        interp.exec("import rlcompleter, readline");
        interp.exec("readline.parse_and_bind('tab: complete')");

        Py.getSystemState().setClassLoader(
                this.getClass().getClassLoader());
        interp.exec("import sys");
        interp.exec("import javax.swing as swing");
        interp.exec("import java.lang as lang");
        interp.exec("import org.opensim.modeling as modeling");
        interp.exec("from org.opensim.console.gui import *");
        interp.exec("from org.opensim.console.OpenSimPlotter import *");
        
        //engine.exec("import org.opensim.tracking as tools");
        //interp.setIn(in);
        interp.setOut(out);
        interp.setErr(err);
        setTabSize(4);
        // setup the event handlers and input processing
        // setup the document filter so output and old text can't be modified
        addKeyListener(this);
        filter = new ConsoleFilter(this);
        ((AbstractDocument) getDocument()).setDocumentFilter(filter);
        // start text and edit location
        setText("Jython Interactive Console\r\n>>> ");
        // editStart = getText().length();
        getCaret().setDot(editStart);
       //((JLineConsole)interp).interact();
    }
 
Example #24
Source File: JythonScriptEngine.java    From spork with Apache License 2.0 4 votes vote down vote up
/**
 * get the state of modules currently loaded
 * @return a map of module name to module file (absolute path)
 */
private static Map<String, String> getModuleState() {
    // determine the current module state
    Map<String, String> files = new HashMap<String, String>();
    PyStringMap modules = (PyStringMap) Py.getSystemState().modules;
    for (PyObject kvp : modules.iteritems().asIterable()) {
        PyTuple tuple = (PyTuple) kvp;
        String name = tuple.get(0).toString();
        Object value = tuple.get(1);
        // inspect the module to determine file location and status
        try {
            Object fileEntry = null;
            Object loader = null;
            if (value instanceof PyJavaPackage ) {
                fileEntry = ((PyJavaPackage) value).__file__;
            } else if (value instanceof PyObject) {
                // resolved through the filesystem (or built-in)
                PyObject dict = ((PyObject) value).getDict();
                if (dict != null) {
                    fileEntry = dict.__finditem__("__file__");
                    loader = dict.__finditem__("__loader__");
                } // else built-in
            }   // else some system module?

            if (fileEntry != null) {
                File file = resolvePyModulePath(fileEntry.toString(), loader);
                if (file.exists()) {
                    String apath = file.getAbsolutePath();
                    if (apath.endsWith(".jar") || apath.endsWith(".zip")) {
                        // jar files are simple added to the pigContext
                        files.put(apath, apath);
                    } else {
                        // determine the relative path that the file should have in the jar
                        int pos = apath.lastIndexOf(File.separatorChar + name.replace('.', File.separatorChar));
                        if (pos > 0) {
                            files.put(apath.substring(pos + 1), apath);
                        } else {
                            files.put(apath, apath);
                        }
                    }
                } else {
                    LOG.warn("module file does not exist: " + name + ", " + file);
                }
            } // else built-in
        } catch (Exception e) {
            LOG.warn("exception while retrieving module state: " + value, e);
        }
    }
    return files;
}
 
Example #25
Source File: JythonEngineWrapper.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
@Override
public ScriptEngine getEngine() {
    ScriptEngine engine = super.getEngine();
    Py.getSystemState().path.append(Py.newString(options.getModulePath()));
    return engine;
}
 
Example #26
Source File: JythonSupport.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
/** Perform static, one-time initialization */
private static boolean init()
{
    final List<String> paths = new ArrayList<>();
    try
    {
        final Properties pre_props = System.getProperties();
        final Properties props = new Properties();

        // Compare jython setup with
        // org.csstudio.display.builder.runtime.script.internal.JythonScriptSupport

        // Disable cachedir to avoid creation of cachedir folder.
        // See http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#java-package-scanning
        // and http://wiki.python.org/jython/PackageScanning
        props.setProperty(RegistryKey.PYTHON_CACHEDIR_SKIP, "true");

        // By default, Jython compiler creates bytecode files xxx$py.class
        // adjacent to the *.py source file.
        // They are owned by the current user, which typically results in
        // problems for other users, who can either not read them, or not
        // write updates after *.py changes.
        Options.dont_write_bytecode = true;

        // With python.home defined, there is no more
        // "ImportError: Cannot import site module and its dependencies: No module named site"
        // Skipping the site import still results in faster startup
        props.setProperty("python.import.site", "false");

        // Prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
        props.setProperty("python.console.encoding", "UTF-8");

        // Options: error, warning, message (default), comment, debug
        // props.setProperty("python.verbose", "debug");

        // No need to add numjy,
        // it's found on __pyclasspath__ because it's in the scan-model module

        // Add scan script paths
        for (String pref_path : ScanServerInstance.getScanConfig().getScriptPaths())
        {
            // Resolve built-in examples
            if (pref_path.startsWith(PathStreamTool.EXAMPLES))
            {
                String path = PathStreamTool.patchExamplePath(pref_path);
                final URL url = ScanServerInstance.class.getResource(path);
                if (url == null)
                    throw new Exception("Error in scan script path " + pref_path);
                path = url.toExternalForm();
                // Patch file:/path/to/the_file.jar!/path/within
                if (path.startsWith("file:"))
                    path = path.substring(5);
                path = path.replace(".jar!", ".jar");
                paths.add(path);
            }
            else // Add as-is
                paths.add(pref_path);
        }

        props.setProperty("python.path", paths.stream().collect(Collectors.joining(java.io.File.pathSeparator)));

        PythonInterpreter.initialize(pre_props, props, new String[0]);
        final PySystemState state = Py.getSystemState();
        final PyVersionInfo version = PySystemState.version_info;
        logger.log(Level.INFO, "Initial Paths for Jython " + version.major + "." + version.minor + "." + version.micro + ":");
        for (Object o : state.path)
            logger.log(Level.INFO, " * " + Objects.toString(o));

        // Display Builder Scripts would sometimes fail in "from ... import ..." with this error:
        //
        // File "..jython-standalone-2.7.1.jar/Lib/warnings.py", line 226, in warn
        // IndexError: index out of range: 0
        //
        // That version of Lib/warnings.py:226 tries to read sys.argv[0],
        // so setting sys.argv[0] avoids the crash.
        state.argv.clear();
        state.argv.add("ScanServerScript");
    }
    catch (Exception ex)
    {
        logger.log(Level.SEVERE, "Once this worked OK, but now the Jython initialization failed. Don't you hate computers?", ex);
        return false;
    }
    return true;
}
 
Example #27
Source File: DocTest.java    From elasticsearch-inout-plugin with Apache License 2.0 4 votes vote down vote up
private void resetInterpreter() {
    interp = new PythonInterpreter(null, new PySystemState());
    sys = Py.getSystemState();
}
 
Example #28
Source File: JythonScriptSupport.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
/** Perform static, one-time initialization */
private static boolean init()
{
    try
    {
        final Properties pre_props = System.getProperties();
        final Properties props = new Properties();

        // Jython 2.7(b3) needed these to set sys.prefix and sys.executable.
        // Locate the jython plugin for 'home' to allow use of /Lib in there
        // final String home = null; // getPluginPath("org.python.jython", "/");

        // If left undefined, initialization of Lib/site.py fails with
        // posixpath.py", line 394, in normpath AttributeError:
        // 'NoneType' object has no attribute 'startswith'
        // props.setProperty("python.home", home);
        // props.setProperty("python.executable", "None");

        // Disable cachedir to avoid creation of cachedir folder.
        // See http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#java-package-scanning
        // and http://wiki.python.org/jython/PackageScanning
        props.setProperty(RegistryKey.PYTHON_CACHEDIR_SKIP, "true");

        // By default, Jython compiler creates bytecode files xxx$py.class
        // adjacent to the *.py source file.
        // They are owned by the current user, which typically results in
        // problems for other users, who can either not read them, or not
        // write updates after *.py changes.
        // There is no way to have them be created in a different, per-user directory.
        // C Python honors an environment variable PYTHONDONTWRITEBYTECODE=true to
        // disable its bytecode files, but Jython only checks that in its command line launcher.
        // Use the same environment variable in case it's defined,
        // and default to disabled bytecode, i.e. the safe alternative.
        if (System.getenv("PYTHONDONTWRITEBYTECODE") == null)
            Options.dont_write_bytecode = true;
        else
            Options.dont_write_bytecode = Boolean.parseBoolean(System.getenv("PYTHONDONTWRITEBYTECODE"));

        // With python.home defined, there is no more
        // "ImportError: Cannot import site module and its dependencies: No module named site"
        // Skipping the site import still results in faster startup
        props.setProperty("python.import.site", "false");

        // Prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
        props.setProperty("python.console.encoding", "UTF-8");

        // This will replace entries found on JYTHONPATH
        final String python_path = Preferences.python_path;
        if (! python_path.isEmpty())
            props.setProperty("python.path", python_path);

        // Options: error, warning, message (default), comment, debug
        // props.setProperty("python.verbose", "debug");
        // org.python.core.Options.verbose = Py.DEBUG;

        PythonInterpreter.initialize(pre_props, props, new String[0]);
        final PySystemState state = Py.getSystemState();
        final PyList paths = state.path;

        // Add the examples/connect2j to path.
        // During development, examples are in
        // "file:/some/path/phoebus/applications/display/model/target/classes/examples"
        final String examples = ModelPlugin.class.getResource("/examples").toString();
        if (examples.startsWith("file:"))
            paths.add(examples.substring(5) + "/connect2j");
        // In the compiled version, examples are in
        // "jar:file:/some/path/display-model-0.0.1.jar!/examples"
        else if (examples.startsWith("jar:file:"))
            paths.add(examples.substring(9).replace("jar!/", "jar/") + "/connect2j");
        else
            logger.log(Level.WARNING, "Cannot locate examples/connect2j from " + examples);

        final PyVersionInfo version = PySystemState.version_info;
        logger.log(Level.INFO, "Initial Paths for Jython " + version.major + "." + version.minor + "." + version.micro + ": " + paths);

        // Scripts would sometimes fail in "from ... import ..." with this error:
        //
        // File "..jython-standalone-2.7.1.jar/Lib/warnings.py", line 226, in warn
        // IndexError: index out of range: 0
        //
        // That version of Lib/warnings.py:226 tries to read sys.argv[0],
        // so setting sys.argv[0] avoids the crash.
        // Since state is shared by all scripts in a display,
        // set it to a generic "DisplayBuilderScript"
        state.argv.clear();
        state.argv.add("DisplayBuilderScript");

        return true;
    }
    catch (Exception ex)
    {
        logger.log(Level.SEVERE, "Once this worked OK, but now the Jython initialization failed. Don't you hate computers?", ex);
    }
    return false;
}
 
Example #29
Source File: MeteoInfoLab.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void runScript(String args[], String fn, int idx) {
    //String ext = GlobalUtil.getFileExtension(fn);
    //registerFonts();
    org.meteoinfo.global.util.FontUtil.registerWeatherFont();

    System.out.println("Running Jython script...");
    PySystemState state = new PySystemState();
    if (args.length > idx + 1) {
        for (int i = idx + 1; i < args.length; i++) {
            state.argv.append(Py.newStringOrUnicode(args[i]));
            //state.argv.append(new PyString(args[i]));
        }
    }
    //state.setdefaultencoding("utf-8");
    //PythonInterpreter interp = new PythonInterpreter(null, state);
    MyPythonInterpreter interp = new MyPythonInterpreter(null, state);

    boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().
            getInputArguments().toString().contains("jdwp");
    String path, toolboxPath, miPath;
    if (isDebug) {
        path = "D:/MyProgram/java/MeteoInfoDev/MeteoInfo/MeteoInfoLab/pylib";
        toolboxPath = "D:/MyProgram/java/MeteoInfoDev/toolbox";
        miPath = "D:/MyProgram/Distribution/Java/MeteoInfo/MeteoInfo";
    } else {
        //String pluginPath = GlobalUtil.getAppPath(FrmMain.class) + File.separator + "plugins";
        //List<String> jarfns = GlobalUtil.getFiles(pluginPath, ".jar");
        miPath = GlobalUtil.getAppPath(FrmMain.class);
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("windows") && miPath.substring(0, 1).equals("/")) {
            miPath = miPath.substring(1);
        }
        path = miPath + File.separator + "pylib";
        toolboxPath = miPath + "/toolbox";;
    }

    try {
        interp.exec("import sys");
        interp.exec("import os");
        interp.exec("import datetime");
        interp.exec("sys.path.append('" + path + "')");
        //interp.exec("from milab import *");
        interp.execfile(path + "/milab.py");
        if (!isDebug) {
            interp.exec("sys.path.append('" + toolboxPath + "')");
            //interp.exec("from toolbox import *");
        }
        interp.exec("mipylib.plotlib.miplot.batchmode = True");
        interp.exec("mipylib.plotlib.miplot.isinteractive = False");
        interp.exec("mipylib.migl.mifolder = '" + miPath + "'");
        System.out.println("mipylib is loaded...");
        interp.execfile(fn);
    } catch (Exception e) {
        e.printStackTrace();
        //System.exit(0);
    } finally {
        System.exit(0);
    }
}