Java中调用python程序
2018-02-08 15:34
344 查看
Java中调用python程序
首先需要安装jython,搜索并下载jython_installer.jar,双击安装,并到安装目录下复制jython.jar到相应的java项目下,并添加到项目的库中。import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
public class Main {
public static void main(String[] args) {
// 初始化python解析器
PythonInterpreter interpreter = new PythonInterpreter();
System.out.println("==================Start Process=================");
// interpreter.execfile("pyfile/detect.py");
// 加载Python类库
PySystemState state = Py.getSystemState();
state.path.add("D:\\Users\\Seavan_CC\\Anaconda3\\Lib\\site-packages");
//将Python函数解析为Java函数
PyFunction func = (PyFunction)interpreter.get("transPython",PyFunction.class);
//设置参数
String str = null;
// 调用函数并保存返回值
PyObject pyObject = func.__call__(new PyString(str));
interpreter.execfile("pyfile/detect.py");
System.out.println("==================End=================");
}
}若不知道运行程序缺少的类库是什么,可以在运行如下Java程序,打印出目前已添加的Java类库
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
public class Main {
public static void main(String[] args) {
// 初始化python解析器
PythonInterpreter interpreter = new PythonInterpreter();
System.out.println("==================Start Process=================");
// interpreter.execfile("pyfile/detect.py");
// 加载Python类库
PySystemState state = Py.getSystemState();
System.out.println(state.path.toString());
System.out.println("==================End=================");
}
}
并在命令行或Java IDE运行如下代码:
最后通过如下代码,添加缺少的类库:
PySystemState state = Py.getSystemState();
state.path.add(" ");
相关文章推荐
- python3调用java的webService小程序
- python调用java程序--jpype
- idea中通过java程序直接调用python文件
- Java程序中调用Python脚本的方法
- Runtime.getRuntime().exec()实现Java调用python程序
- 使用Jpype在python中调用Java程序
- python 调用 Java程序
- 使用JPype实现Python调用JAVA程序
- Java程序中调用Python脚本的方法
- python调用java程序--jpype
- Java调用Python程序并向Python传值
- python调用java程序--jpype
- Java程序中实现调用Python脚本的方法详解
- [Python]Python如何调用Java程序
- Java调用Python程序方法总结(最全最详细)
- 在java中实现调用简单的c程序
- PL/SQL 调用Java程序(Linux)
- 用java程序调用ffmpeg执行视频文件格式转换flv
- 通过java 程序调用数据库中的存储过程
- 把python程序用jython编译为java的jar包