您的位置:首页 > 编程语言 > Python开发

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(" ");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java Python Jython