1. 程式人生 > 實用技巧 >java呼叫Python,以控制檯方式執行

java呼叫Python,以控制檯方式執行

1、java程式碼

package com;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        restartPy();
    }

    public synchronized static void restartPy() {
        try {
            //cmd /c 表示執行後關閉    start cmd /c 開啟一個視窗 執行後關閉
            String cmd = "cmd /c start cmd /c python";
            String exeName = "D:/pyTest.py";
            String py = "python.exe";
            if (processIsRun(py)) {
                killProcess(py);
            }
            Runtime.getRuntime().exec(cmd + " " + exeName);
            if (processIsRun(py)) {
                System.out.println("----------------啟動python  成功------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 殺掉一個程序
     */
    public static void killProcess(String name) {
        try {
            String[] cmd = {"tasklist"};
            Process proc = Runtime.getRuntime().exec(cmd);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String string_Temp = in.readLine();
            while (string_Temp != null) {
                // System.out.println(string_Temp);
                if (string_Temp.indexOf(name) != -1) {
                    Runtime.getRuntime().exec("taskkill /F /IM " + name);
                    System.out.println("殺死程序  " + name);
                }
                string_Temp = in.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判斷程序是否存在
     */
    public static boolean processIsRun(String ProjectName) {
        boolean flag = false;
        try {
            Process p = Runtime.getRuntime().exec("cmd /c tasklist ");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream os = p.getInputStream();
            byte b[] = new byte[256];
            while (os.read(b) > 0)
                baos.write(b);
            String s = baos.toString();
            if (s.indexOf(ProjectName) >= 0) {
                flag = true;
            } else {
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}

2、python程式碼

python 程式碼空格嚴格

import sys
import time

def fun(img):
    print(img)
    while True:
        print("java call Python ok")
        time.sleep(1)

    
if __name__ == '__main__':
    img = sys.argv[0]
    fun(img)