Java Code Examples for org.python.util.PythonInterpreter#exec()

The following examples show how to use org.python.util.PythonInterpreter#exec() . 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: InterpreterUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private static synchronized PythonInterpreter initPythonInterpreter(String[] args, String pythonPath, String scriptName) {
	if (!jythonInitialized) {
		// the java stack traces within the jython runtime aren't useful for users
		System.getProperties().put("python.options.includeJavaStackInExceptions", "false");
		PySystemState.initialize(System.getProperties(), new Properties(), args);

		pythonInterpreter = new PythonInterpreter();

		pythonInterpreter.getSystemState().path.add(0, pythonPath);

		pythonInterpreter.setErr(System.err);
		pythonInterpreter.setOut(System.out);

		pythonInterpreter.exec("import " + scriptName);
		jythonInitialized = true;
	}
	return pythonInterpreter;
}
 
Example 2
Source File: FrmMain.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Load an application
 *
 * @param plugin Application
 */
public void loadApplication(Application plugin) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    try {
        PythonInterpreter interp = this.getConsoleDockable().getInterpreter();
        String path = plugin.getPath();
        interp.exec("import " + path);
        interp.exec("from " + path + ".loadApp import LoadApp");
        PyObject loadClass = interp.get("LoadApp");
        PyObject loadObj = loadClass.__call__();
        IPlugin instance = (IPlugin) loadObj.__tojava__(IPlugin.class);
        instance.setApplication(FrmMain.this);
        instance.setName(plugin.getName());
        plugin.setPluginObject(instance);
        plugin.setLoad(true);
        instance.load();
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.setCursor(Cursor.getDefaultCursor());
}
 
Example 3
Source File: JythonServer.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
/**
 * The main thread for this class invoked by Thread.run()
 *
 * @see java.lang.Thread#run()
 */
public void run() {
    PythonInterpreter p = new PythonInterpreter();
    for (String name : this.locals.keySet()) {
        p.set(name, this.locals.get(name));
    }

    URL jarUrl = JythonServer.class.getProtectionDomain().getCodeSource().getLocation();
    String jarPath = jarUrl.getPath();
    if (jarUrl.getProtocol().equals("file")) {
        // If URL is of type file, assume that we are in dev env and set path to python dir.
        // else use the jar file as is
        jarPath = jarPath + "../../src/main/python/";
    }

    p.exec("import sys");
    p.exec("sys.path.append('" + jarPath + "')");
    p.exec("from debugserver import run_server");
    if (this.host == null) {
    	p.exec("run_server(port=" + this.port + ", locals=locals())");
    } else {
    	p.exec("run_server(port=" + this.port + ", host='" + this.host + "', locals=locals())");
    }
}
 
Example 4
Source File: InterpreterUtils.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the Jython interpreter and executes a python script.
 *
 * @param factory environment factory
 * @param scriptDirectory the directory containing all required user python scripts
 * @param scriptName the name of the main python script
 * @param args Command line arguments that will be delivered to the executed python script
 */
public static void initAndExecPythonScript(PythonEnvironmentFactory factory, java.nio.file.Path scriptDirectory, String scriptName, String[] args) {
	String[] fullArgs = new String[args.length + 1];
	fullArgs[0] = scriptDirectory.resolve(scriptName).toString();
	System.arraycopy(args, 0, fullArgs, 1, args.length);

	PythonInterpreter pythonInterpreter = initPythonInterpreter(fullArgs, scriptDirectory.toUri().getPath(), scriptName);

	pythonInterpreter.set("__flink_env_factory__", factory);
	pythonInterpreter.exec(scriptName + ".main(__flink_env_factory__)");
}
 
Example 5
Source File: MeteoInfoMap.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void runScript(String args[], String fn, int idx) {
    String ext = GlobalUtil.getFileExtension(fn);
    System.out.println("Running Jython script...");
    //PySystemState state = Py.getSystemState();
    //Py.getSystemState().setdefaultencoding("utf-8");
    PySystemState state = new PySystemState();
    //state.setdefaultencoding("utf-8");
    if (args.length > idx + 1) {
        for (int i = idx + 1; i < args.length; i++) {
            state.argv.append(new PyString(args[i]));
        }
    }

    PythonInterpreter interp = new PythonInterpreter(null, state);
    String pluginPath = GlobalUtil.getAppPath(FrmMain.class) + File.separator + "plugins";
    List<String> jarfns = GlobalUtil.getFiles(pluginPath, ".jar");
    String path = GlobalUtil.getAppPath(FrmMain.class) + File.separator + "pylib";
    interp.exec("import sys");
    //interp.set("mis", mis);
    interp.exec("sys.path.append('" + path + "')");
    //interp.exec("import mipylib");
    //interp.exec("from mipylib.miscript import *");
    //interp.exec("from meteoinfo.numeric.JNumeric import *");
    for (String jarfn : jarfns) {
        interp.exec("sys.path.append('" + jarfn + "')");
    }
    interp.execfile(fn);
    System.exit(0);
}
 
Example 6
Source File: FrmAppsManager.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Application readPyApp(String path, String fileName) {
    try {
        Application plugin = new Application();
        plugin.setPath(path);
        plugin.setClassName("LoadApp");
        PythonInterpreter interp = this.parent.getConsoleDockable().getInterpreter();
        interp.exec("import " + path);
        interp.exec("from " + path + ".loadApp import LoadApp");
        PyObject loadClass = interp.get("LoadApp");
        PyObject loadObj = loadClass.__call__();
        IPlugin instance = (IPlugin) loadObj.__tojava__(IPlugin.class);
        plugin.setPluginObject(instance);
        return plugin;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 7
Source File: TestPython.java    From albert with MIT License 5 votes vote down vote up
@Test
public void  test1(){
	PythonInterpreter interpreter = new PythonInterpreter();

       interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
       interpreter.exec("print days[1];");
}
 
Example 8
Source File: JythonTest.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private void testInterpreter(final PythonInterpreter python) throws Exception
{
    // Run on new threads to get fresh thread-locals
    final ExecutorService new_executor = Executors.newCachedThreadPool();

    final String script = "import sys\nresult = sys.path";
    final Callable<String> test_run = () ->
    {
        // System.out.println("Executing on " + Thread.currentThread().getName());
        final PyCode code = python.compile(script);
        python.exec(code);
        return python.get("result").toString();
    };

    final List<Future<String>> futures = new ArrayList<>();
    final long end = System.currentTimeMillis() + 1000L;
    while (System.currentTimeMillis() < end)
    {
        for (int i=0; i<50; ++i)
            futures.add(new_executor.submit(test_run));
        for (Future<String> future : futures)
        {
            final String result = future.get();
            //System.out.println(result);
            assertThat(result, containsString("always"));
            assertThat(result, containsString("special"));
        }
        futures.clear();
    }
    new_executor.shutdown();
}
 
Example 9
Source File: MenuController.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
public static String markdownToHtml(MdTextController index, String chaine) {
    PythonInterpreter console = index.getPyconsole();
    console.set("text", chaine);
    console.exec("render = mk_instance.convert(text)");
    PyString render = console.get("render", PyString.class);
    return render.toString();
}
 
Example 10
Source File: AndroidDriver.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public void executeCommand(String cmd){
	PythonInterpreter interpreter = new PythonInterpreter();
	Vector<AndroidDriver> drivers = new Vector();
	drivers.add(this);
	interpreter.set("device", drivers);
	interpreter.exec(cmd); 
}
 
Example 11
Source File: ScriptRunner.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public Map<String, PyObject> runStringAndGet(String executablePath, String script, Collection<String> names)
/*     */   {
/* 142 */     initPython(executablePath);
/* 143 */     PythonInterpreter python = new PythonInterpreter();
/* 144 */     python.exec(script);
/*     */ 
/* 146 */     ImmutableMap.Builder builder = ImmutableMap.builder();
/* 147 */     for (String name : names) {
/* 148 */       builder.put(name, python.get(name));
/*     */     }
/* 150 */     return builder.build();
/*     */   }
 
Example 12
Source File: JPythonInterpreterDriver.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
public void executeScript(String script)
      throws InterpreterDriver.InterpreterException {
   try {
      _interpreter = new PythonInterpreter();
      _interpreter.exec(script);
   }
   catch (PyException ex) {
      throw new InterpreterDriver.InterpreterException(ex);
   }
}
 
Example 13
Source File: ScriptRunner.java    From AndroidRobot with Apache License 2.0 4 votes vote down vote up
public void runString(String executablePath, String script) {
/* 130 */     initPython(executablePath);
/* 131 */     PythonInterpreter python = new PythonInterpreter();
/* 132 */     python.exec(script);
/*     */   }
 
Example 14
Source File: MonkeyPlugin.java    From sikuli-monkey with MIT License 4 votes vote down vote up
@Override
public boolean apply(PythonInterpreter anInterpreter) {
    anInterpreter.exec(readInitScript());
    return true;
}
 
Example 15
Source File: PyCodeUtil.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void exec(byte[] compiledCode, PythonInterpreter interpreter) throws Exception{
        PyCode pyCode = BytecodeLoader.makeCode(NAME, compiledCode, null);
        interpreter.exec(pyCode);
}