Howto multithreaded jython scripts running from java? Howto multithreaded jython scripts running from java? multithreading multithreading

Howto multithreaded jython scripts running from java?


It is a pity that PyCode instances aren't immutable (there are a lot of public members on the classes).

You can precompile a reusable script using this code:

// TODO: generate this namefinal String name = "X";byte[] scriptBytes = PyString.to_bytes(script);CompilerFlags flags = Py.getCompilerFlags();ByteArrayOutputStream ostream = new ByteArrayOutputStream();Module.compile(parser.parse(new ByteArrayInputStream(scriptBytes), "exec",    "<>", flags), ostream, name, "<>", false, false, false, flags);byte[] buffer = ostream.toByteArray();Class<PyRunnable> clazz = BytecodeLoader.makeClass(name, null, buffer);final Constructor<PyRunnable> constructor = clazz    .getConstructor(new Class[] { String.class });

You can then use the constructor to produce PyCode instances for the script whenever you need one:

 PyRunnable r = constructor.newInstance(name); PyCode pc = r.getMain();

I would be the first to admit that this is not a good way of doing things and probably speaks volumes about my inexperience with Jython. However, it is significantly faster than compiling every time. The code works under Jython 2.2.1, but won't compile under Jython 2.5 (nor will yours).


PythonInterpreter is expensive, this code will use only one.

#action.pydef execute(filename, action_locals):    #add caching of compiled scripts here    exec(compile(open(filename).read(), filename, 'exec'), action_locals)//class variable, only one interpreterPythonInterpreter pi;//run once in init() or constructorpi = new PythonInterpreter();//could do more initialization herepi.exec("import action");//every script executionPyObject pyActionRunner = pi.eval("action.execute");PyString pyActionName = new PyString(script_path);PyDictionary pyActionLocals = new PyDictionary();pyActionLocals.put("variable_1", "value_1");pyActionLocals.put("variable_x", "value_x")pyActionRunner.__call__(pyActionName, pyActionLocals);#example_script.pyprint variable_1, variable_x