pyjnius
pyjnius copied to clipboard
Loading multiple components using pyjnius
I'm trying to leverage two isolated modules which internally call pyjnius. Let's call them step_a and step_b.
So
step_a.py
import pyjnius
import jnius_config
.
.
jnius_config.add_classpath(jar_path_to_a)
pyjnius.autoclass('...some.File')
step_b.py
import pyjnius
import jnius_config
.
.
jnius_config.add_classpath(jar_path_to_b)
pyjnius.autoclass('...some.File')
orchestrator.py
import step_a
import step_b
# call and perform operation on step_a and step_b output
This is resulting in a
jnius_config.add_classpath(jar_path)
File "/usr/local/lib/python3.7/site-packages/jnius_config.py", line 54, in add_classpath
raise ValueError("VM is already running, can't set classpath")
ValueError: VM is already running, can't set classpath
error. Is it not possible to have multiple jnius instances running from a module ? I would hope jnius spawns a new VM or offers spawning a new process so isolated processes can be run which internally use jnius.
hm, looks like if we know we already started the jvm, we could just add the classpath at runtime https://stackoverflow.com/questions/45232522/how-to-set-classpath-of-a-running-jvm-in-cjni (and you can probably use this method directly in your project, just making sure the jvm is loaded first)
@ctrueden this issue and comment look very interesting for classpath updates at runtime, if we ever re-visit this.
Hi, I would like to asked if the original problem has been solved and how? I have similar issue, and solve it by
- having all jar file in one directory
- having import jnius_config, jnius_config.add_classpath() with *. in one .py file
- in all other .py files, having from pyjnius import autocalss in each function before using any class in the jar
But now, I need to implement Java class in Python, where the syntax is class A (PythonJavaClass) .... and from jnius import PythonJavaClass must be declared in advance. The previous trick does not work in this case.
Can you help?
I solved it.
Actually the jnius_config.add_classpath() must follow import jnius_config immediately in one .py file which is called before any other files where pyjnius is also used.
File 1: import jnius_config jnius_config.add_classpath(<path/*>) [other import] from jnius import autoclass ...
Other files: from jnius import autoclass ... class A(.. ):