當前位置: 首頁>>代碼示例>>Java>>正文


Java Py.getSystemState方法代碼示例

本文整理匯總了Java中org.python.core.Py.getSystemState方法的典型用法代碼示例。如果您正苦於以下問題:Java Py.getSystemState方法的具體用法?Java Py.getSystemState怎麽用?Java Py.getSystemState使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.python.core.Py的用法示例。


在下文中一共展示了Py.getSystemState方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: setupSystemState

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * Call to ensure that an interpreter is set up and configured and
 * able to load the relevant bundles.
 */
public static synchronized void setupSystemState(String... bundleNames) {

	ClassLoader loader=null;
	if (configuredState==null) { // Relies on setupSystemState() being called early in the server startup.
		loader = createJythonClassLoader(PySystemState.class.getClassLoader());
		initializePythonPath(loader);
	}

PySystemState state = Py.getSystemState();
if (state==configuredState) return;

if (loader==null) {
	// Then someone else has changed the PySystemState
	// They will not have added our
		loader = createJythonClassLoader(state.getClassLoader());   // Don't clobber their working.
}
	state.setClassLoader(loader);

setJythonPaths(state);       // Tries to ensure that enough of jython is on the path
setSpgGeneratorPaths(state, bundleNames); // Adds the scripts directory from points
	Py.setSystemState(state);

	configuredState = state;
}
 
開發者ID:eclipse,項目名稱:scanning,代碼行數:29,代碼來源:JythonInterpreterManager.java

示例2: stop

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * Get rid of the interpreter.
 */
public void stop() {
	if (interp != null) {
		// PySystemState.exit(); // the big hammar' throws like Thor
		interp.cleanup();
		interp = null;
	}

	if (interpThread != null) {
		interpThread.interrupt();
		interpThread = null;
	}

	if (inputQueueThread != null) {
		inputQueueThread.interrupt();
		inputQueueThread = null;
	}

	thread.interruptAllThreads();
	Py.getSystemState()._systemRestart = true;
}
 
開發者ID:glaudiston,項目名稱:project-bianca,代碼行數:24,代碼來源:Python.java

示例3: CreateFromPython

import org.python.core.Py; //導入方法依賴的package包/類
public void CreateFromPython()
	{
		PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());

		PySystemState sys = Py.getSystemState();

		sys.path.append(new PyString(context.settings.GetModelPath()));

		if(context.settings.GetSysPath() != null)
			sys.path.append(new PyString(context.settings.GetSysPath()));

		/*
// some magic to pass context to all python modules
		interpreter.set("context", context);
		interpreter.set("model_service", model_service);
		interpreter.exec("import __builtin__");
		interpreter.exec("__builtin__.context = context");
		interpreter.exec("__builtin__.model_service = model_service");*/

		interpreter.execfile(context.settings.GetModelPath() + '/' + context.settings.GetModelMain());

		interpreter.cleanup();

		UpdateDefinedSensors();
	}
 
開發者ID:srcc-msu,項目名稱:octotron_core,代碼行數:26,代碼來源:ExecutionService.java

示例4: JythonObjectFactory

import org.python.core.Py; //導入方法依賴的package包/類
public JythonObjectFactory(Class<T> javaClass, String moduleName, String className, String... bundleNames) {

		JythonInterpreterManager.setupSystemState(bundleNames);
		PySystemState state = Py.getSystemState();

		this.javaClass = javaClass;
		PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__"));
		PyObject module = importer.__call__(Py.newString(moduleName));
		pyClass = module.__getattr__(className);
	}
 
開發者ID:eclipse,項目名稱:scanning,代碼行數:11,代碼來源:JythonObjectFactory.java

示例5: main

import org.python.core.Py; //導入方法依賴的package包/類
public static void main(String[] args) {
	interpreter = new PythonInterpreter();
	createWindow();
	initOpenGL();
	try {
		interpreter.execfile(Main.class.getClassLoader().getResourceAsStream("init.py"));
		PySystemState sys = Py.getSystemState();
		sys.path.append(new PyString(getJARPath()));
		//TextureRenderer.init();
		interpreter.execfile("script.py");
		idle();
	} catch(Exception e) {
		JOptionPane.showMessageDialog(null, e.toString(), "Python error", JOptionPane.ERROR_MESSAGE);
	}
}
 
開發者ID:bartvbl,項目名稱:pixeltoy,代碼行數:16,代碼來源:Main.java

示例6: createPythonInterpreter

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * 
 */
public void createPythonInterpreter() {
	// TODO - check if exists - destroy / de-initialize if necessary
	PySystemState.initialize();
	interp = new PythonInterpreter();

	PySystemState sys = Py.getSystemState();
	if (rootPath != null) {
		sys.path.append(new PyString(rootPath));
	}
	if (modulesDir != null) {
		sys.path.append(new PyString(modulesDir));
	}

	// add self reference
	// Python scripts can refer to this service as 'python' regardless
	// of the actual name
	/*
	 * String selfReferenceScript =
	 * String.format("from org.myrobotlab.service import Runtime\n" +
	 * "from org.myrobotlab.service import Python\n" +
	 * "python = Runtime.getService(\"%s\")\n\n", getName()); // TODO - //
	 * deprecate //+ "runtime = Runtime.getInstance()\n\n" +
	 * "myService = Runtime.create(\"%1$s\",\"Python\")\n",
	 * getSafeReferenceName(this.getName())); PyObject compiled =
	 * getCompiledMethod("initializePython", selfReferenceScript, interp);
	 * interp.exec(compiled);
	 */

	/*
	 * String self = String.format("myService = Runtime.getService(\"%s\")",
	 * getName()); PyObject compiled = getCompiledMethod("initializePython",
	 * self, interp); interp.exec(compiled);
	 */

	String selfReferenceScript = "from org.myrobotlab.service import Runtime\n" + "from org.myrobotlab.service import Python\n"
			+ String.format("%s = Runtime.getService(\"%s\")\n\n", getSafeReferenceName(getName()), getName()) + "Runtime = Runtime.getInstance()\n\n"
			+ String.format("myService = Runtime.getService(\"%s\")\n", getName());
	PyObject compiled = getCompiledMethod("initializePython", selfReferenceScript, interp);
	interp.exec(compiled);
}
 
開發者ID:glaudiston,項目名稱:project-bianca,代碼行數:44,代碼來源:Python.java

示例7: init

import org.python.core.Py; //導入方法依賴的package包/類
/** Perform static, one-time initialization */
private static boolean init()
{
    try
    {
        final Properties pre_props = System.getProperties();
        final Properties props = new Properties();

        // Locate the jython plugin for 'home' to allow use of /Lib in there
        final String home = getPluginPath("org.python.jython", "/");
        if (home == null)
            throw new Exception("Cannot locate jython bundle. No OSGi?");

        // Jython 2.7(b3) needs these to set sys.prefix and sys.executable.
        // 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(PySystemState.PYTHON_CACHEDIR_SKIP, "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");

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

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

        PythonInterpreter.initialize(pre_props, props, new String[0]);

        final PyList paths = Py.getSystemState().path;
        paths.add(getPluginPath("org.csstudio.display.builder.runtime", "scripts"));

        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;
}
 
開發者ID:kasemir,項目名稱:org.csstudio.display.builder,代碼行數:56,代碼來源:JythonScriptSupport.java

示例8: getSentimentAnalyzer

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * Construct and
 * return an {@link ISentimentAnalyzer} instance backed by an instance of
 * the
 * Python tool, loading its training and feature-set data from the given
 * filenames.
 * 
 * @param classifierFilename
 *            the name of the serialized classifier pickle file for the
 *            Python tool to load
 * @param featuresFilename
 *            the name of the serialized feature-set pickle file for the
 *            Python tool to load
 * @return the Python sentiment analysis tool instance
 * 
 * @throws NullPointerException
 *             if either parameter is {@code null}
 * @throws PySentimentAnalyzer.LoadFailureException
 *             if tool instantiation fails for any
 *             other reason.
 */
public static ISentimentAnalyzer getSentimentAnalyzer(
		String classifierFilename, String featuresFilename)
		throws NullPointerException,
		PySentimentAnalyzer.LoadFailureException {

	String workingDir = System.getProperty("user.dir");
	String pyDir = workingDir + "/py";
	PySystemState sys = Py.getSystemState();
	sys.path.append(new PyString(workingDir));
	sys.path.append(new PyString(pyDir));
	final PySystemObjectFactory factory = new PySystemObjectFactory(sys,
			ISentimentAnalyzer.class, "SentimentAnalyzerP",
			"SentimentAnalyzerP");
	return (ISentimentAnalyzer) factory.createObject(classifierFilename,
			featuresFilename);
}
 
開發者ID:rmachedo,項目名稱:MEater,代碼行數:38,代碼來源:PySentimentAnalyzer.java

示例9: createPythonInterpreter

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * 
 */
public void createPythonInterpreter() {
	// TODO: If the username on windows contains non-ascii characters
	// the Jython interpreter will blow up.
	// The APPDATA environment variable contains the username.
	// as a result, jython sees the non ascii chars and it causes a utf-8
	// decoding error.
	// overriding of the APPDATA environment variable is done in the agent
	// as a work around.

	// work around for 2.7.0
	// http://bugs.jython.org/issue2355

	// ??? - do we need to extract {jar}/Lib/site.py ???

	Properties props = new Properties();

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

	/*
	 * don't respect java accessibility, so that we can access protected
	 * members on subclasses
	 */
	props.put("python.security.respectJavaAccessibility", "false");
	props.put("python.import.site", "false");

	Properties preprops = System.getProperties();

	PythonInterpreter.initialize(preprops, props, new String[0]);

	interp = new PythonInterpreter();

	PySystemState sys = Py.getSystemState();

	if (modulesDir != null) {
		sys.path.append(new PyString(modulesDir));
	}
	log.info("Python System Path: {}", sys.path);

	String selfReferenceScript = "from org.myrobotlab.service import Runtime\n" + "from org.myrobotlab.service import Python\n"
			+ String.format("%s = Runtime.getService(\"%s\")\n\n", getSafeReferenceName(getName()), getName()) + "Runtime = Runtime.getInstance()\n\n"
			+ String.format("myService = Runtime.getService(\"%s\")\n", getName());
	PyObject compiled = getCompiledMethod("initializePython", selfReferenceScript, interp);
	interp.exec(compiled);
}
 
開發者ID:MyRobotLab,項目名稱:myrobotlab,代碼行數:52,代碼來源:Python.java

示例10: getModuleState

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * 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), 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;
}
 
開發者ID:sigmoidanalytics,項目名稱:spork-streaming,代碼行數:54,代碼來源:JythonScriptEngine.java

示例11: getModuleState

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:sigmoidanalytics,項目名稱:spork,代碼行數:54,代碼來源:JythonScriptEngine.java

示例12: getModuleState

import org.python.core.Py; //導入方法依賴的package包/類
/**
 * 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;
            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__");
                } // else built-in
            }   // else some system module?

            if (fileEntry != null) {
                File file = new File(fileEntry.toString());
                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), 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;
}
 
開發者ID:PonIC,項目名稱:PonIC,代碼行數:53,代碼來源:JythonScriptEngine.java

示例13: resetInterpreter

import org.python.core.Py; //導入方法依賴的package包/類
private void resetInterpreter() {
    interp = new PythonInterpreter(null, new PySystemState());
    sys = Py.getSystemState();
}
 
開發者ID:crate,項目名稱:elasticsearch-inout-plugin,代碼行數:5,代碼來源:DocTest.java


注:本文中的org.python.core.Py.getSystemState方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。