Java代码中调用python程序
Java代码中调用python程序
制作人:全心全意
使用jython调用python程序(不可使用第三方库)
导入依赖jar包
下载地址:https://www.jython.org/download.html
maven导入:
<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.0</version> </dependency>
java调用示例:
package com.zq.jpy;
import java.io.UnsupportedEncodingException;
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class Jpy {
public static void main(String[] args) {
// -Dpython.console.encoding=UTF-8
// 直接执行python命令
System.out.println("=============直接执行python命令==============");
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a='hello world'; ");
interpreter.exec("print(a);");
// 执行python脚本
System.out.println("=============执行python脚本==============");
interpreter.execfile("E:/jpy.py"); // 该py脚本中不可包含第三方库
// 调用python脚本中的函数
System.out.println("=============调用python脚本中的函数==============");
// interpreter.execfile("E:/jpy.py"); // 该py脚本中不可包含第三方库
PyFunction pyFunction = interpreter.get("add", PyFunction.class);
PyObject pyObject1 = pyFunction.__call__(new PyInteger(5), new PyInteger(3)); // 调用函数
System.out.println(pyObject1);
PyObject pyObject2 = pyFunction.__call__(new PyString("wo"), new PyString("ni")); // 调用函数
System.out.println(pyObject2.toString());
PyObject pyObject3 = pyFunction.__call__(Py.newStringUTF8("我"),
Py.newStringUTF8("你")); // 调用函数中使用了中文
try {
System.out.println(
new String(pyObject3.toString().getBytes("iso8859-1"), "utf-8")); // 对返回的中文解码在编码
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
python程序示例:
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
print("我是python脚本")
def add(a,b):
print(a+b)
return a + b;
使用Runtime.getRuntime调用python程序(可以使用第三方库)
请参照:Java调用CMD命令

浙公网安备 33010602011771号