本文整理汇总了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;
}
示例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;
}
示例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();
}
示例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);
}
示例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);
}
}
示例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);
}
示例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;
}
示例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);
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
示例13: resetInterpreter
import org.python.core.Py; //导入方法依赖的package包/类
private void resetInterpreter() {
interp = new PythonInterpreter(null, new PySystemState());
sys = Py.getSystemState();
}