cooooool
cooooool

Reputation: 425

Running python script from jar file

I have been working on java app that uses python script to run some 3d visualization, it worked when I was running it from intellij but once I created jar file it just doesn't run. OS: MAC OS

How I run script: Process p1 = Runtime.getRuntime().exec("python3 vizualize3D.py");

Upvotes: 1

Views: 1518

Answers (3)

Heisenbug
Heisenbug

Reputation: 484

I've tried all solutions provided; inorder to run a python script present inside a jar file.

My best bet would be to NOT keep the python files inside jar, which ultimately worked for me. Instead keep them at same location/level with jar and use following code to invoke python script from a java class inside the jar.

String pyScriptPath = "./py_script.py"; 

ProcessBuilder pb = new ProcessBuilder("python3" + pyScriptPath);
Process process = pb.start();

So the dir structure would be something like:

../rootFolder
    - javaProgram.jar
    - py_script.py

Upvotes: 0

cooooool
cooooool

Reputation: 425

The problem had multiple layers and solutions: 1. I didn't put .py file in jar build config 2. After putting it I always got an exception that it is null because of a typo in code 3. After trying many ways to run it this one worked Cannot run python script from java jar . The important thing is to check if you added py file to the build config and to run it in a proper way since python cannot runt files from the zip and compressed states.

Upvotes: 2

James_D
James_D

Reputation: 209418

Assuming the script is in the jar file, you can get an input stream from the resource, and use it as the input to a Process created from the python interpreter:

// Note: the path to the script here is relative to the current class
// and follows strict resource name rules, since this is in a jar file
InputStream script = getClass().getResourceAsStream("visualize3D.py");

// The following creates a process to run python3.
// This assumes python3 is on the system path. Provide the full
// path to the python3 interpreter (e.g. /usr/bin/python3) if it's
// not on the path.

// The - option to python3 instructs it to execute a script provided
// as standard input.

Process process = new ProcessBuilder("python3", "-")
    .start() ;
OutputStream out = process.getOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while((read = script.read(buffer)) != -1) {
    pos.write(buffer, 0, read);
}
script.close();

For details on getting the correct path for the script, see How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?

Upvotes: 0

Related Questions