1

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.

That1Guy
  • 7,075
  • 4
  • 47
  • 59
k9b
  • 1,457
  • 4
  • 24
  • 54
  • I don't think that the jar option is 'messy'. Read this: http://baojie.org/blog/2014/06/16/call-java-from-python/ – Nir Alfasi Oct 05 '15 at 18:19
  • 4
    Possible duplicate of [Calling Java from Python](http://stackoverflow.com/questions/3652554/calling-java-from-python) – Nir Alfasi Oct 05 '15 at 18:20

2 Answers2

4

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.

HugoMailhot
  • 1,275
  • 1
  • 10
  • 19
  • Thanks, I'll take a look. In the standalone java class, how would I worry about importing the sikuli-java.jar? In java I add it to the project libraries, but how would I do this in a standalone .java file being referenced by python through pyjnius? – k9b Oct 05 '15 at 19:02
  • @k9b I added an example that shows you how to use a JAR file. – HugoMailhot Oct 05 '15 at 19:21
  • Thank you very much. Makes tons of sense! – k9b Oct 05 '15 at 20:51
1

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()
sirfz
  • 4,097
  • 23
  • 37