【技巧】Java执行Python脚本
方案一
命令行
//执行命令 可以通过命令行方式传参
Process exec = Runtime.getRuntime().exec("python /home/jar/demo/a.py /home/jar/demo/test.txt");
// System.out.println(exec.);
int i = exec.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(
exec.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
//结果
System.out.println(line);
}
方案二
需要依赖
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.3</version>
</dependency>
<!-- hutool工具类-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.20</version>
</dependency>
ScriptEngine pythonEngine = ScriptUtil.getPythonEngine();
String py = "" +
"import pandas as pd\n" +
"print('123456')";
Object eval = pythonEngine.eval(py);
//结果
System.out.println(eval);