Java调用本地Python脚本

package com.yang.ftpdemo.pyzbar;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PyZbarTest {

    public static void main(String[] args) {
        //这里传递的其实是OS级别的命令
        System.out.println(ExecutePyzbar("python", "C:\\Users\\Tyrael\\Desktop\\pyzbar\\PyZbarTest.py", null));
    }

    private static String ExecutePyzbar(String lang, String scriptPath, String base64) {
        String[] arguments = new String[]{lang, scriptPath};
        try {
            Process process = Runtime.getRuntime().exec(arguments);
            int re = process.waitFor();
            
            //java代码中的process.waitFor()返回值为0表示调用python脚本成功,1表示调用失败,这个有点【反直觉】
            if (re == 0) {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));) {
                    return in.readLine();
                }
            } else {
                System.err.println("脚本调用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
posted @ 2020-08-07 09:53  JaxYoun  阅读(382)  评论(0编辑  收藏  举报