Java 调用 Python脚本 踩坑
前言
前端时间研究Java调用opencv后,需要Python对图像进行处理,便转战Java调用Python
1、首先安装Anaconda3
在安装过程中需勾选配置环境变量
2、process.waitFor()
执行返回9009,但是不报错,返回为0才是正常
此时在cmd输入where python
D:\Program\Python>where python
E:\Program\Anaconda3\python.exe
C:\Users\A\AppData\Local\Microsoft\WindowsApps\python.exe
发现是两个python.exe,这就是罪魁祸首,需前往C:\Users\A\AppData\Local\Microsoft\WindowsApps
下删除python.exe,程序正常运行
参考:关于Java调用python脚本waitFor:9009及cmd执行python无响应、无输出问题
Java代码
package com; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CallPython { public static void main(String[] args) { String[] args1 = new String[]{"E:\\Program\\Anaconda3\\python.exe", "D:/Program/Python/videoRec.py", "1", "2"}; System.out.println("result=" + callPython(args1)); } private static String callPython(String... param) { String result = ""; Process process = null; BufferedReader reader = null; try { process = Runtime.getRuntime().exec(param); reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (!"".equals(line)) { result = line; } } System.out.println("waitFor=" + process.waitFor()); } catch (Exception e) { e.printStackTrace(); } finally { if (process != null) { process.destroyForcibly(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } } }
jiafa.py脚本文件
import sys def fun(a,b): print(a+b) return (a+b) if __name__ == '__main__': a = sys.argv[1] b = sys.argv[2] fun(a,b)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-12-04 11.【Linq】