Practical use of Java class/JAR in Python?

2019-03-01 03:52发布

问题:

I spent significant amount of time looking for this and explore many solutions.

This is related to this thread. Calling Java from Python

In the end, after testing:

Pyjnius : Cannot install in Windows.

Py4J: can install on windows, but using Gateway is a bit heavy.

JPype: Python 3 installed in 5 mins, can load 50Mo JAR without any issues. Good thing is the syntax is completely merged with Python syntax... https://github.com/tcalmant/jpype-py3

Just Wondering, if any people has developed real world wrapping application of Java in Python (ie running on a production server) with big size JAR ?

回答1:

To save time to many people, I post the module I used for JPype, this is working nicel to load JAR.

import jpype as jp; import numpy as np; import os as os
jarpath= r"D:\zjavajar\\"
mavenurl= r"http://mvnrepository.com/artifact/"



# StartJVM (add "-Xmx" option with 1024M if crash due to not enough memory )
def importJAR(path1="", path2="", path3="", path4=""):
   classpath = path1
   if path2 != "":  classpath = os.pathsep.join((classpath, path2))   
   if path3 != "":  classpath = os.pathsep.join((classpath, path3))
   if path4 != "":  classpath = os.pathsep.join((classpath, path4))        
   jp.startJVM(jp.getJVMPath(),"-ea", "-Djava.class.path=%s" % classpath)


def showLoadedClass(): #Code to see the JAR loaded.
   classloader = jp.java.lang.ClassLoader.getSystemClassLoader(); vv= []; 
   for x in classloader.getURLs():  vv.append(x.toString());         
   return vv


def loadSingleton(class1):  single= jp.JClass(class1);  return Single.getInstance()


def java_print(x):  jp.java.lang.System.out.println(x)   #Print in Java Console