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)