William William - 1 month ago 10
Java Question

How to call Python script from a Java JAR file

Currently I'm working on a simulation project that involve both Java and Python.

The simulator interface is written in Java Swing. The solver/engine is written in Python.

I'm using Eclipse to develop the project. I use Process and Runtime to call the Python Script with some parameters. I use pydev inside Eclipse to run the Python script.

Now, after I export the project to a JAR file, the Python code is located inside the JAR as a folder. Apparently, java won't be able to call the Python Script in the JVM anymore. Is there a way to use JAR to call Python Script and parse the simulation results?

Jython might be a option, but I'm trying to see if there is simpler way without change significant amount of code from the original Python script.

Thank you so much,

  • Part1:(import .jar file as library in Eclipse)

You make a new project to Eclipse(name:Project1) When you open it you see JRE System Library[java version something]

1.right click on JRE System Library

2.Go->Build Path->Configure Build Path

3.You can see (Up right Corner the button[add jars or add external jars]

*Here i advise you to choose the first(add jars) but..

*First copy(or move) the Python.jar inside the project((example):Project 1)

*Now you can add it with the button(add jars).

*In this way when you finish your project the Python.jar will be imported inside the project(If you export it as a .jar from Eclipse)

..Now you can call any method of Python.jar just(import it into the class you want to use and call it)

Let me know if that works for you...

Part 2:

  • Running a file which is inside the eclipse Project(warning! before export it to jar):

1.Way(Following the path of file)

 try {
    Runtime.getRuntime().exec("cmd /c start C:/NameOfEclipseProject/Project/src/pack(Package)/script.py");

    } catch (IOException e) { e.printStackTrace(); }

2.i will add them soon..(it has been time since i used them try to find)

  • Running the script after export project to jar(warning! after export to jar)

Check this question link