I am running a Python project, yet there is one library (sikuli) that is loads easier to work with in Java. I was wondering if there was some way I could grant my python program access to the Java class and somehow have the JVM interpret the calls to the Java class from Python.
The other alternative is to make a .jar with all my methods and then just run the jar with arguments with a .subprocess command in Python, which is a little bit messy but would also get the job done.
-
I don't think that the jar option is 'messy'. Read this: baojie.org/blog/2014/06/16/call-java-from-pythonNir Alfasi– Nir Alfasi2015年10月05日 18:19:34 +00:00Commented Oct 5, 2015 at 18:19
-
4Possible duplicate of Calling Java from PythonNir Alfasi– Nir Alfasi2015年10月05日 18:20:49 +00:00Commented Oct 5, 2015 at 18:20
2 Answers 2
Take a look at Pyjnius. It lets you import a Java class as a Python object and it exposes its methods in a transparent, pythonic way.
Basic example: Using a class in a JAR file
java_resource_jar_path = "/path/to/jar/directory"
jnius_config.set_classpath(java_resource_jar_path)
from jnius import autoclass
# from jnius import JavaException
# You might have to import JavaException if your class happens to throw exceptions
TheJavaClass = autoclass(path.in.the.jar.file.to.class) # No ".class", no parentheses
python_instance_of_the_Java_class = TheJavaClass()
At this point, python_instance_of_the_Java_class has all the methods of your Java class.
3 Comments
Jpype1 allows you to start the JVM with custom jars in your classpath which allows you to virtually use any third-party Java library via Python.
import jpype
jpype.startJVM(jpype.getDefaultJVMPath(), '-ae', "-Djava.class.path=./MyLibrary.jar")
pkg = jpype.JPackage('com').site.myclasses
javaobj = pkg.MyClass()
javaobj.javaMethod()