Python Script Execution
Python4j Python Script Execution

Script execution overview

Python4j runs and manages python interpreters as well as the GIL for a user. When a user attempts to execute a python script, they are calling in to cpython's PyRun rountines. This invokes cpython directly. This functionality can be found in the PythonExecutioner
When invoking cpython, we actually also wrap the execution code the user specifies in a python script. This script can be found here. This script mainly ensures we can properly print python stack traces if an error occurs. It does this by ensuring stdout/stderr for the given in memory python interpreter are flushed properly.

Initialization

Note that before a python script can execute, python4j needs to initialize itself. This happens in the static initialization block of PythonExecutioner Be aware of that when executing python scripts.

Python variable input and output

Python4j allows users to pass in and retrieve in memory python variables. A simple example:
1
try(PythonGIL pythonGIL = PythonGIL.lock()) {
2
List<PythonVariable> inputs = new ArrayList<>();
3
inputs.add(new PythonVariable<>("x", PythonTypes.STR, "Hello "));
4
inputs.add(new PythonVariable<>("y", PythonTypes.STR, "World"));
5
String code = "print(x + y)";
6
PythonExecutioner.exec(code, inputs, null);
7
}
Copied!
In our case here, we're not retreiving variables, but just passing 2 strings in for printing.
For retrieving variables, we can do either of the following:
1
String code = "a = 5\nb = '10'\nc = 20.0";
2
List<PythonVariable> vars = PythonExecutioner.execAndReturnAllVariables(code);
Copied!
Exec and return all variables allows us to retrieve any variable tha twas created during the python execution by name. The returned PythonVariables will be named as they were in the python script.
Optionally, a user may also specify a list of variables to be returned. This can be achieved by passing in an output variable list to PythonExecutioner.exec(..) as follows:
1
try(PythonGIL pythonGIL = PythonGIL.lock()) {
2
List<PythonVariable> inputs = new ArrayList<>();
3
inputs.add(new PythonVariable<>("x", PythonTypes.STR, "Hello "));
4
inputs.add(new PythonVariable<>("y", PythonTypes.STR, "World"));
5
PythonVariable out = new PythonVariable<>("z", PythonTypes.STR);
6
String code = "z = x + y";
7
PythonExecutioner.exec(code, inputs, Collections.singletonList(out));
8
9
}
Copied!

Execution in a multi threaded environment

Python4j is capable of multi threaded execution of python scripts. The user can manage multiple threads by ensuring that all python calls are wrapped in the double try/with block mentioned in the overview By locking the GIL and watching the garbage collection in any python call, the GIL management is automatically handled for the user.
Optionally, a user may also use the PythonContextManager - creating one context per thread. A "context" is essentially a separate python interpreter with its own variables, memory etc.