Java:在Java中调用python文件执行
目录
- 一、Java内置Jpython库(不推荐)
- 1.1 下载与使用
- 1.2 缺陷
- 二、使用Runtime.getRuntime()执行脚本⽂件
- 2.1 使用
- 2.2 缺陷
- 三、利用cmd调用python文件
- 3.1 使用
- 3.2 优化
一、Java内置Jpython库(不推荐)
1.1 下载与使用
可以在官网下载jar包,官网
或者使用maven进行jar包下载
<dependency><groupId>org.python</groupId><artifactId>jython-standalone</artifactId><version>2.7.0</version>
</dependency>
执行代码样例:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a=[5,2,3,9,4,0]; ");
interpreter.exec("print(sorted(a));");
1.2 缺陷
Jython内置的库有限,而且很多库不存在,会报no model的错误,所以这里不推荐大家使用。
二、使用Runtime.getRuntime()执行脚本⽂件
2.1 使用
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;publicclass Demo1 {publicstaticvoid main(String[] args) {Process proc;// 编译器是pythonString exe = "python";// py文件存的绝对路径String path = "D:\\NLP.py";// 传入的参数String args = "今天过的很开心";try {proc = Runtime.getRuntime().exec(exe + ' ' + path + ' ' + args);// 执⾏py⽂件// ⽤输⼊输出流来截取结果BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));String line = null;while ((line = in.readLine()) != null) {System.out.println(line);}in.close();proc.waitFor();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} }
}
2.2 缺陷
如果在你的python中,会使用自己包中的其他python文件中的函数,那么很有可能无法导入,但是不会报错,只会返回一个null。
三、利用cmd调用python文件
3.1 使用
这个方法就类似于在cmd中,使用 python file.py 参数 直接执行python文件一样
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;publicclass Demo1 {publicstaticvoid main(String[] args) {Process proc;// 编译器是pythonString exe = "cmd.exe";// py文件存的绝对路径String path = "D:\\NLP.py";// 传入的参数String args = "今天过的很开心";try {proc = Runtime.getRuntime().exec(exe + " \c start " + path + ' ' + args);// 执⾏py⽂件proc.waitFor();} catch (Exception e) {e.printStackTrace();} }
}
3.2 优化
考虑到python是否正在进行,或者是否调用python,可设置一些函数用于辅助:
- 这里没有使用参数,直接对文件进行读取,传参可能会存在编码问题,Java默认UTF-8,cmd是GBK
package com.Lee.utils;import java.io.*;public class NLPUtils {// NLP处理public static String NLP(String data) throws Exception{try {inputToFile(data);}catch (Exception e){e.printStackTrace();}System.out.println("调用python程序");Process pcs = null;String py = "python.exe";try {if(processIsRun(py))killProcess(py);System.out.println("start");pcs = Runtime.getRuntime().exec("cmd.exe /c start F://python_project//NLP.bat");pcs.waitFor();if(processIsRun(py)){System.out.println("正在执行");Thread.currentThread().sleep(30000);}System.out.println("end");}catch (Exception e){e.printStackTrace();}String result = "";try {System.out.println("out:" + outputFromFile());result = outputFromFile();}catch (Exception e){e.printStackTrace();}return result;}// 清空文件public static void clearInfoForFile(String fileName) {File file =new File(fileName);try {if(!file.exists()) {file.createNewFile();}FileWriter fileWriter =new FileWriter(file);fileWriter.write("");fileWriter.flush();fileWriter.close();} catch (Exception e) {e.printStackTrace();}}// 输入文件,参数为输出字符串public static void inputToFile(String input) throws Exception{// 写入前清空clearInfoForFile("F:\\python_project\\input.txt");//创建写入流FileWriter writer=new FileWriter("F:\\python_project\\input.txt");// 写入writer.write(input + "\r\n");//关闭资源writer.flush();writer.close();}// 读取文件public static String outputFromFile() throws Exception{InputStreamReader isr = new InputStreamReader(new FileInputStream("F:\\python_project\\output.txt"), "GBK");BufferedReader read = new BufferedReader(isr);String s = null;String result = "";while((s = read.readLine()) != null)result += s;isr.close();read.close();return result;}// 杀掉一个进程public static void killProcess(String name) {try {String[] cmd = {"tasklist"};Process proc = Runtime.getRuntime().exec(cmd);BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));String string_Temp = in.readLine();while (string_Temp != null) {// System.out.println(string_Temp);if (string_Temp.indexOf(name) != -1) {Runtime.getRuntime().exec("taskkill /F /IM " + name);System.out.println("杀死进程 " + name);}string_Temp = in.readLine();}} catch (Exception e) {e.printStackTrace();}}// 判断进程是否存在public static boolean processIsRun(String ProjectName) {boolean flag = false;try {Process p = Runtime.getRuntime().exec("cmd /c tasklist ");ByteArrayOutputStream baos = new ByteArrayOutputStream();InputStream os = p.getInputStream();byte b[] = new byte[256];while (os.read(b) > 0)baos.write(b);String s = baos.toString();if (s.indexOf(ProjectName) >= 0) {flag = true;} else {flag = false;}} catch (Exception e) {e.printStackTrace();}return flag;}
}
Java:在Java中调用python文件执行相关推荐
- java执行python脚本_使用Runtime.getRuntime().exec()在java中调用python脚本
举例有一个Python脚本叫test.py,现在想要在Java里调用这个脚本.假定这个test.py里面使用了拓展的包,使得pythoninterpreter之类内嵌的编译器无法使用,那么只能采用ja ...
- java中调用python
在Java中调用Python </h1><div class="clear"></div><div class="postBod ...
- 在Spark Scala/Java应用中调用Python脚本,会么?
摘要:本文将介绍如何在 Spark scala 程序中调用 Python 脚本,Spark java程序调用的过程也大体相同. 本文分享自华为云社区<[Spark]如何在Spark Scala/ ...
- 教你如何在Spark Scala/Java应用中调用Python脚本
摘要:本文将介绍如何在 Spark scala 程序中调用 Python 脚本,Spark java程序调用的过程也大体相同. 本文分享自华为云社区<[Spark]如何在Spark Scala/ ...
- 在Java中调用Python,java面试题,java初级笔试题
写在最前面,我总结出了很多互联网公司的面试题及答案,并整理成了文档,以及各种学习的进阶学习资料,免费分享给大家.扫码加微信好友进[程序员面试学习交流群],免费领取.也欢迎各位一起在群里探讨技术. 写在 ...
- java怎么调用python_如何在Java中调用Python代码
Jython(原JPython),是一个用2113Java语言写的Python解释5261器.在没有第三方模块的情况下4102,通常选择利用Jython来调用1653Python代码,它是一个开源的J ...
- 在Java中调用Python
写在前面 参考:https://www.cnblogs.com/nuccch/p/8435693.html 在微服务架构大行其道的今天,对于将程序进行嵌套调用的做法其实并不可取,甚至显得有些愚蠢.当然 ...
- java调用第三方dll文件 源码_C++调用python文件(包含第三方库)
本文内容主要参考以下两篇文章: 武军:C++中调用python(VS2017)zhuanlan.zhihu.com C++调用python的那些坑(详细教程步骤)_giser_xupf的博客-CSD ...
- Java如何跨语言调用Python/R训练的模型
在 如何使用sklearn进行在线实时预测(构建真实世界中可用的模型) 这篇文章中,我们使用 sklearn + flask 构建了一个实时预测的模型应用.无论是 sklearn 还是 flask,都 ...
最新文章
- linux c 启动程序吗,Linux下C程序启动时的系统调用
- mongodb3 分片集群平滑迁移
- rownum 的一点儿研究
- VINS-Mono:一种鲁棒且通用的单目视觉惯性系统
- ionic+angularJS+iOS混合开发app的学习资料介绍和基本步骤(干货)
- mongodb内存映射原理
- 到2025年将保持不变的热门流行技术
- 实例40:python
- 切换数据库_如何快速切换到其他数据库实例
- 异常:System.BadImageFormatException,未能加载正确的程序集XXX
- install and use zookeeper C client API
- 游戏设计规则探秘之宾语
- chaincode java_基于Hyperledger Fabric交易系统帐户的钱包模型的java Chaincode实例
- MFC界面库BCGControlBar Pro for MFC v33.1 - 更适配Windows 11
- 孙玄:“玄姐”,特立独行的架构师
- 计算机应用软件论文范文,计算机论文范文大全集(计算机应用论文范文5000字)
- 20190707 - FE:使用 Charles 在 IphoneX 上抓包
- iis日志分析 seo必备技能
- 产品质量异常的正确处理流程
- qt android png透明,Qt处理照片实现白色背景转透明