zoukankan      html  css  js  c++  java
  • Java 调用 Python脚本 踩坑

    前言

    前端时间研究Java调用opencv后,需要Python对图像进行处理,便转战Java调用Python

    1、首先安装Anaconda3

    在安装过程中需勾选配置环境变量

    2、process.waitFor()执行返回9009,但是不报错,返回为0才是正常

    此时在cmd输入where python

    D:ProgramPython>where python
    E:ProgramAnaconda3python.exe
    C:UsersAAppDataLocalMicrosoftWindowsAppspython.exe

    发现是两个python.exe,这就是罪魁祸首,需前往C:UsersAAppDataLocalMicrosoftWindowsApps下删除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)
    
    
  • 相关阅读:
    Vue项目端口号占用
    理解vuex -- vue的状态管理模式
    2018-7-10杂记
    JS 数组操作总结
    JS 字符串操作总结
    【javascript练习题】函数
    【javascript练习题】this指针和作用域
    canal实时同步mysql binlog到rabbitmq
    Hexo+GitHub+Netlify一站式搭建属于自己的博客网站
    Git学习原版手稿
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/14087867.html
Copyright © 2011-2022 走看看