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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With