本文整理汇总了Java中org.python.util.PythonInterpreter.initialize方法的典型用法代码示例。如果您正苦于以下问题:Java PythonInterpreter.initialize方法的具体用法?Java PythonInterpreter.initialize怎么用?Java PythonInterpreter.initialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.python.util.PythonInterpreter
的用法示例。
在下文中一共展示了PythonInterpreter.initialize方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: SimulatorImpl
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
/**
* Constructs a new instance.
*/
public SimulatorImpl() {
// initialize Python interpreter
Properties properties = new Properties();
properties.setProperty("python.home", StaticConfiguration.JYTHON_HOME);
properties.setProperty("python.path", StaticConfiguration.JYTHON_LIB);
PythonInterpreter.initialize(System.getProperties(), properties, new String[] {""});
// initialize the shutdown hook to terminate application properly
Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
if (OS.getType() == OS.Type.WINDOWS) {
// create hidden window to handle WM_CLOSE messages on Windows to react to taskkill
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
}
}
示例2: initPython
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
private void initPython(String executablePath, Collection<String> pythonPath, String[] argv)
/* */ {
/* 160 */ Properties props = new Properties();
/* */
/* 163 */ StringBuilder sb = new StringBuilder();
/* 164 */ sb.append(System.getProperty("java.class.path"));
/* 165 */ for (String p : pythonPath) {
/* 166 */ sb.append(":").append(p);
/* */ }
/* 168 */ props.setProperty("python.path", sb.toString());
/* */
/* 173 */ props.setProperty("python.verbose", "error");
/* */
/* 176 */ props.setProperty("python.executable", executablePath);
/* */
/* 178 */ PythonInterpreter.initialize(System.getProperties(), props, argv);
/* */
/* 180 */ //String frameworkDir = System.getProperty("java.ext.dirs");
/* 181 */ //File monkeyRunnerJar = new File(frameworkDir, "monkeyrunner.jar");
/* 182 */ //if (monkeyRunnerJar.canRead())
/* 183 */ // PySystemState.packageManager.addJar(monkeyRunnerJar.getAbsolutePath(), false);
/* */ }
示例3: init
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
private void init()
{
// System.out.println("Initializing on " + Thread.currentThread().getName());
final Properties pre_props = System.getProperties();
final Properties props = new Properties();
String home = PythonInterpreter.class
.getProtectionDomain().getCodeSource().getLocation().toString();
System.out.println("Jython home: " + home);
assertThat(home, not(nullValue()));
if (home.contains(".jar"))
System.out.println("Jython provided as JAR");
home = home.replace("file:", "");
props.setProperty("python.home", home);
// props.setProperty("python.executable", "None");
props.setProperty(PySystemState.PYTHON_CACHEDIR_SKIP, "true");
props.setProperty("python.import.site", "false");
// props.setProperty("python.console.encoding", "UTF-8");
props.setProperty("python.path", "/tmp/always");
// props.setProperty("python.verbose", "debug");
// Options.verbose = Py.DEBUG;
PythonInterpreter.initialize(pre_props, props, new String[0]);
}
示例4: main
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
public static void main(String[] args) {
String directory = System.getProperty("user.home") + File.separator + ".fvb-modules";
File dir = new File(directory);
if (dir.exists()) {
try {
Properties props = new Properties();
props.setProperty("python.path", directory);
PythonInterpreter.initialize(System.getProperties(), props, new String[]{""});
PythonInterpreter interpreter = new PythonInterpreter();
// PyCode code = interpreter.compile(new FileReader(new File(directory, "TestModule.py")));
interpreter.exec("from TestModule import TestModule");
//interpreter.eval(code);
// System.out.println(interpreter.getLocals());
PyObject object = interpreter.get("TestModule");
PyObject buildObject = object.__call__();
ExternalModule ext = (ExternalModule) buildObject.__tojava__(ExternalModule.class);
System.out.println(ext.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例5: execute
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
/**
* Executes a python script, returning its output or not.
*
* @param fileName the filename of the python script to execute
* @param redirectOutput true to redirect outputs and return them, false otherwise
* @param arguments the arguments to pass to the python script
* @return the output of the python script execution (combined standard and error outputs) or null if outputs were not
* redirected
* @throws PyException in case of exception during Python script execution
*/
public static String execute(String fileName, boolean redirectOutput, String... arguments) throws PyException {
Properties properties = new Properties();
properties.setProperty("python.home", StaticConfiguration.JYTHON_HOME);
properties.setProperty("python.path", StaticConfiguration.FORMATTER_DIR);
PythonInterpreter.initialize(System.getProperties(), properties, new String[] {""});
try (PythonInterpreter interp = new PythonInterpreter(new org.python.core.PyStringMap(),
new org.python.core.PySystemState())) {
StringWriter output = null;
if (redirectOutput) {
output = new StringWriter();
interp.setOut(output);
interp.setErr(output);
}
interp.cleanup();
interp.exec("import sys;sys.argv[1:]= [r'" + StringUtils.join(arguments, "','") + "']");
interp.exec("__name__ = '__main__'");
interp.exec("execfile(r'" + fileName + "')");
return redirectOutput ? output.toString() : null;
}
}
示例6: PyEngine
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
public PyEngine() {
String pythonPath = getPythonPath();
String enginePath = Paths.get(pythonPath).getParent().getParent().resolve("lib/jython-standalone-2.7.0.jar/Lib").toString();
Properties props = new Properties();
props.put("python.home","lib");
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site","false");
PythonInterpreter.initialize(System.getProperties(), props, new String[0]);
engine = new ScriptEngineManager().getEngineByName("python");
engine.put("enginePath", enginePath);
engine.put("pythonPath", pythonPath);
PyEngine.eval(engine,
"import sys",
"sys.path.append(enginePath)",
"sys.path.append(pythonPath)",
"import uroborosqlfmt",
"from uroborosqlfmt import api",
"from uroborosqlfmt.config import LocalConfig",
"from uroborosqlfmt.commentsyntax import Doma2CommentSyntax");
}
示例7: initPython
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
private static void initPython(String executablePath,
Collection<String> pythonPath, String[] argv) {
Properties props = new Properties();
// Build up the python.path
StringBuilder sb = new StringBuilder();
sb.append(System.getProperty("java.class.path"));
for (String p : pythonPath) {
sb.append(":").append(p);
}
props.setProperty("python.path", sb.toString());
/** Initialize the python interpreter. */
// Default is 'message' which displays sys-package-mgr bloat
// Choose one of error,warning,message,comment,debug
props.setProperty("python.verbose", "error");
// This needs to be set for sys.executable to function properly
props.setProperty("python.executable", executablePath);
PythonInterpreter.initialize(System.getProperties(), props, argv);
String frameworkDir = System.getProperty("java.ext.dirs");
File wookieerRunnerJar = new File(frameworkDir, "wookieerunner.jar");
if (wookieerRunnerJar.canRead()) {
PySystemState.packageManager.addJar(wookieerRunnerJar.getAbsolutePath(), false);
}
}
示例8: initPythonIntepreter
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
private void initPythonIntepreter()
{
Properties postProperties = new Properties();
postProperties.put( "python.path", getCxxTestPythonHome( cxxTest.getCxxTestHome() ).getAbsolutePath() );
getLog().debug( "Initialising Jython with properties=" + postProperties );
PythonInterpreter.initialize( System.getProperties(), postProperties, null );
}
示例9: ScriptModuleLoader
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
/**
* Initialises a ScriptModuleLoader
*
* @param fvb the instance of {@link FreeVoteBot} where the modules should be loaded to
*/
public ScriptModuleLoader(FreeVoteBot fvb) {
this.fvb = fvb;
Properties props = new Properties();
props.setProperty("python.path", new File(".", "target").getAbsolutePath()
+ ":" + LoadModules.MODULES_DIR.getAbsolutePath());
PythonInterpreter.initialize(System.getProperties(), props,
new String[]{""});
}
示例10: onStartCommand
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isRunning) {
return Service.START_REDELIVER_INTENT;
}
isRunning = true;
startReason = intent.getExtras().getString("com.runassudo.pyandroid.START_REASON");
try {
File mainfile = new File(Environment.getExternalStorageDirectory(), "PyAndroid/main.py");
// Set Python properties
Properties props = new Properties();
props.put("python.import.site", "false");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.verbose", "debug");
Properties preprops = System.getProperties();
// Pass ourselves in
HashMap<PyObject,PyObject> localsMap = new HashMap<PyObject,PyObject>();
localsMap.put(new PyString("__service__"), Py.java2py(this));
PyDictionary localsDict = new PyDictionary(localsMap);
// Launch Python
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter(localsDict);
interpreter.execfile(new FileInputStream(mainfile));
} catch (Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(LaunchPyService.this, "An error occurred!", Toast.LENGTH_LONG).show();
}
});
Log.e("PyAndroid", "An error occurred!", e);
appendLog("An error occurred!");
appendLog(Log.getStackTraceString(e));
stopSelf();
}
return Service.START_REDELIVER_INTENT;
}
示例11: init
import org.python.util.PythonInterpreter; //导入方法依赖的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;
}
示例12: createPythonInterpreter
import org.python.util.PythonInterpreter; //导入方法依赖的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);
}
示例13: main
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
@Override
protected Map<String, List<PigStats>> main(PigContext pigContext, String scriptFile)
throws IOException {
PigServer pigServer = new PigServer(pigContext, false);
// register dependencies
String jythonJar = getJarPath(PythonInterpreter.class);
if (jythonJar != null) {
pigServer.registerJar(jythonJar);
}
File f = new File(scriptFile);
if (!f.canRead()) {
throw new IOException("Can't read file: " + scriptFile);
}
// TODO: fis1 is not closed
FileInputStream fis1 = new FileInputStream(scriptFile);
if (hasFunction(fis1)) {
registerFunctions(scriptFile, null, pigContext);
}
if (pigContext.getProperties().get(PigContext.PIG_CMD_ARGS_REMAINDERS)!=null) {
try {
String[] argv = (String[])ObjectSerializer.deserialize(
pigContext.getProperties().getProperty(PigContext.PIG_CMD_ARGS_REMAINDERS));
PythonInterpreter.initialize(null, null, argv);
} catch (IOException e) {
throw new ExecException("Cannot deserialize command line arguments", e);
}
}
Interpreter.setMain(true);
FileInputStream fis = new FileInputStream(scriptFile);
try {
load(fis, scriptFile, pigServer.getPigContext());
} finally {
fis.close();
}
return getPigStatsMap();
}
示例14: main
import org.python.util.PythonInterpreter; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
// Log4j Configuration
PropertyConfigurator.configure(StaticConfiguration.CONFIG_DIRECTORY + "/log4j.properties");
// log version information
logger.info("QTaste kernel version: " + com.qspin.qtaste.kernel.Version.getInstance().getFullVersion());
logger.info("QTaste testAPI version: " + VersionControl.getInstance().getTestApiVersion(""));
// handle config file name and optional -sutversion
if (args.length < 1 || args.length > 5) {
showUsage();
}
int i = 0;
String campaignFileName = args[i++];
while (i < args.length) {
if (args[i].equals("-engine") && (i + 1 < args.length)) {
logger.info("Using " + args[i + 1] + " as engine configuration file");
TestEngineConfiguration.setConfigFile(args[i + 1]);
i += 2;
} else if (args[i].equals("-sutversion") && (i + 1 < args.length)) {
logger.info("Using " + args[i + 1] + " as SUT version");
TestBedConfiguration.setSUTVersion(args[i + 1]);
i += 2;
} else {
showUsage();
}
}
// start the log4j server
Log4jServer.getInstance().start();
// initialize Python interpreter
Properties properties = new Properties();
properties.setProperty("python.home", StaticConfiguration.JYTHON_HOME);
properties.setProperty("python.path", StaticConfiguration.JYTHON_LIB);
PythonInterpreter.initialize(System.getProperties(), properties, new String[] {""});
CampaignManager campaignManager = CampaignManager.getInstance();
boolean executionResult;
try {
Campaign campaign = campaignManager.readFile(campaignFileName);
executionResult = campaignManager.execute(campaign);
} finally {
shutdown();
}
System.exit(executionResult ? 0 : 1);
}