java调用python代码
2020-02-27 20:25 默默不语 阅读(1699) 评论(0) 编辑 收藏 举报最近做项目时需要用Java调用python的文件,本篇博客介绍用java调用python的代码。
一、使用Jpython来实现用java调用python的代码
1.下载JPython的包
我下载的是jython-2.7-b1.jar,下载好后在项目classpath中添加这个jar包。
2.编写简易python代码
import org.python.util.PythonInterpreter;
import java.util.Properties;
/**
*@author chenmeiqi
*@version 2020年2月26日 下午7:08:24
*/
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
PythonInterpreter interpreter = new PythonInterpreter();
// 运行python语句
interpreter.exec("a = \"hello, Jython\"");
interpreter.exec("print a");
}
}
运行结果:
二、使用Runtime.getRuntime()执行脚本文件
Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在java中唯一一个得到运行时环境的方法。
注:如果执行的Python脚本有引用第三方包的,建议使用此种方式。
代码示例:
import org.python.util.PythonInterpreter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; /** *@author chenmeiqi *@version 2020年2月26日 下午7:08:24 */ public class test { public static void main(String[] args) throws IOException, InterruptedException { // TODO Auto-generated method stub Process proc = Runtime.getRuntime().exec("D:\\Anaconda3\\envs\\py36\\python.exe D:/spider/ItemCF.py"); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); proc.waitFor(); System.out.println("end"); } }
python脚本代码:
print("使用java调用python代码!")
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2018-02-27 《需求工程 ——软件建模与分析》读书笔记03