1. 程式人生 > 實用技巧 >Java呼叫本地Python指令碼

Java呼叫本地Python指令碼

package com.yang.ftpdemo.pyzbar;

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

public class PyZbarTest {

    public static void main(String[] args) {
        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;
    }
}