阅读量:2
要在Java中调用Python脚本,您可以使用以下方法之一:
方法1:使用Runtime类
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class JavaCallPython {
public static void main(String[] args) {
try {
String pythonScriptPath = "/path/to/your/python/script.py";
Process process = Runtime.getRuntime().exec("python " + pythonScriptPath);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法2:使用Jython库 首先,您需要下载Jython库并将其添加到Java项目的类路径中。下载地址:https://www.jython.org/downloads.html
然后,您可以使用以下代码调用Python脚本:
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class JavaCallPython {
public static void main(String[] args) {
try (PythonInterpreter interpreter = new PythonInterpreter()) {
interpreter.execfile("/path/to/your/python/script.py");
PyObject result = interpreter.eval("your_function_name()");
String output = (String) result.__tojava__(String.class);
System.out.println(output);
}
}
}
请注意,这些方法可能需要根据您的项目需求进行调整。
以上就是关于“java如何调用python”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm