Search code examples
javapythonfunctionlanguage-interoperability

How to call java objects and functions from CPython?


I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?

It would be nice to be able to use some java objects too.

Jython is not an option. I must run the python part in CPython.


Solution

  • The easiest thing to do is

    1. Write a trivial CLI for your java "function". (There's no such thing, so I'll assume you actually mean a method function of a Java class.)

      public class ExposeAMethod {
          public static void main( String args[] ) {
               TheClassToExpose  x = new TheClassToExpose();
              x.theFunction();
          }
      }
      
    2. Compile and build an executable JAR file with this as the entry point. Call it ExposeAMethod.jar

    3. Call this from a command created by subprocess.

      import subprocess
      p = subprocess.Popen("java -jar ExposeAMethod.jar", shell=True)
      sts = os.waitpid(p.pid, 0)
      

    This is the minimum. And it's really not much. I count 6 lines of java, 3 lines of Python and you're up and running.

    If you want to pass arguments to this Java class constructor or method function, you'll have to write a few more lines of code. You have two choices.

    • Read the arguments from stdin, write the results on stdout. This is relatively easy and performs really well.

    • Parse the arguments as command-line options to Java, write the results on stdout. This is slightly harder, but generalizes very nicely. The bonus is that you now have a useful command-line Java program that you can reuse.