2017-08-12 128 views
2

我需要在java函数内执行python脚本。我试过的东西,但它不能正常工作用java函数执行python脚本

这里是我的代码:

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

} 

这是我run.sh文件:

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 

当我尝试单独运行Python脚本(使用python reportGeneration.py命令在命令行中)它给了我一个输出,但是当我尝试用java函数执行它时,它没有给出任何输出?我的代码中是否有错误?

在此先感谢

+0

没有你的脚本执行权限? –

+3

你也可以尝试:'Runtime.getRuntime()。exec(“python ReportGeneration/reportGeneration.py”);' –

+0

@ Jean-FrançoisFabre谢谢。你的建议清除了我的错误。但是python脚本没有产生预期的结果。当我试图单独执行它时,我的python脚本完美地工作正常 –

回答

0

您可以使用Jython library运行Java代码中的Python脚本。

例如:

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]); 
} 

} 

如果你的项目是基于Maven的,您可以添加这样的Jython依赖性:

<!-- https://mvnrepository.com/artifact/org.python/jython --> 
<dependency> 
    <groupId>org.python</groupId> 
    <artifactId>jython</artifactId> 
    <version>2.7.0</version> 
</dependency>