pyjnius icon indicating copy to clipboard operation
pyjnius copied to clipboard

Loading multiple components using pyjnius

Open srvxid opened this issue 5 years ago • 4 comments

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.

srvxid avatar Jul 23 '19 18:07 srvxid

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)

tshirtman avatar Jul 27 '19 15:07 tshirtman

@ctrueden this issue and comment look very interesting for classpath updates at runtime, if we ever re-visit this.

hanslovsky avatar Aug 07 '19 11:08 hanslovsky

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?

LilyNL avatar Sep 19 '19 07:09 LilyNL

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(.. ):

LilyNL avatar Sep 19 '19 09:09 LilyNL