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)
原文地址:https://www.cnblogs.com/kikyoqiang/p/14151935.html