java代码中如何运行python脚本呢?
下文笔者讲述java代码中运行python脚本的方法分享,如下所示
实现思路:
1.使用jython-standalone组件直接运行python脚本
2.使用Runtime.getRuntime运行脚本
java运行python前的准备工作
引入jar包
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<!--python版本是2.x还是3.x在这里指定-->
<version>2.7.0</version>
</dependency>
方式1:直接使用PythonInterpreter运行python脚本
import org.python.util.PythonInterpreter
public class JavaRunPython {
public static void main(String[] args) {
//首先调用python的解释器
PythonInterpreter interpreter = new PythonInterpreter();
//选择执行的的Python语句
interpreter.exec("a='hello world'; ");
interpreter.exec("print a;");
}
}
方式2:使用文件保存python脚本,然后运行python脚本文件
import org.python.util.PythonInterpreter;
public class JavaPythonFile {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
//我在这里使用相对路径,注意区分
interpreter.execfile("./pythonfile.py");
}
}
方式3:使用Runtime.getRuntime()运行python脚本文件
import org.python.util.PythonInterpreter;
public class JavaPythonFile {
public static void main(String[] args) {
String[] args1=new String[]{"/home/bin/python","/home/pythonfile.py"};
Process pr=Runtime.getRuntime().exec(args1);
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


