Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute python script with java function

Tags:

java

python

I need to execute python script within java function. I tried something but it's not working properly

Here is my code:

private static void generateReport() {
    try {
        Runtime.getRuntime().exec("python ReportGeneration/reportGeneration.py");
    } catch (IOException e) {
        log.error(e);
    }

}

This is my run.sh file:

CLASSPATH=.:target/classes:target/filter-4.0.0-M20-1.0-SNAPSHOT-jar-with-dependencies.jar
JAVA_OPTS="-Xmx8g -Xms8g"
FULL_EXPERIMENT_DURATION_MINUTES=2
WARM_UP_PERIOD_MINS=1
java $JAVA_OPTS -cp $CLASSPATH  yyy.xxx.sample.common.benchmarks.filter.Benchmark $FULL_EXPERIMENT_DURATION_MINUTES $WARM_UP_PERIOD_MINS

When i try to run python script alone (using python reportGeneration.py command in commandline) it gives me an output but when i try to execute it with java function it's not giving any output? is there any error in my code?

Thanks in advance

like image 386
Gowthamy Vaseekaran Avatar asked Jul 04 '26 23:07

Gowthamy Vaseekaran


1 Answers

You can use Jython library to run python scripts inside java code.

For example:

import org.python.util.PythonInterpreter;

import java.util.Properties;

public class Main {

public static void main(String[] args) {
    initializeJython();
    PythonInterpreter interpreter = new PythonInterpreter();

    interpreter.exec("print \"Hello World\"");
    //interpreter.execfile(); // You can also execute script from a file.
}

private static void initializeJython() {
    Properties props = new Properties();
    props.put("python.console.encoding", "UTF-8");
    props.put("python.import.site", "false"); //Jython doesn't work for me without setting this property to false.

    PythonInterpreter.initialize(System.getProperties(), props, new String[0]);
}

}

If your project is maven based you can add jython dependency like this:

<!-- https://mvnrepository.com/artifact/org.python/jython -->
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython</artifactId>
    <version>2.7.0</version>
</dependency>
like image 137
Michał Stochmal Avatar answered Jul 07 '26 12:07

Michał Stochmal