Java:Java程序通过执行系统命令调用Python脚本

本文实现功能:Java程序调用Python脚本

Python脚本

import sys

def add(x, y):
    return x + y

if __name__ == "__main__":
    print(add(int(sys.argv[1]), int(sys.argv[2])))

直接执行

$ python math.py 1 2
3

Java程序调用Python脚本

package io.github.mouday.utils;

import java.io.*;

/**
 * 执行系统命令
 */
public final class ShellUtil {
    private ShellUtil() {
    }

    /**
     * 操作系统名称
     *
     * @return Mac OS X
     */
    public static String getOsName() {
        return System.getProperty("os.name");
    }

    /**
     * 判断是否为windows操作系统
     *
     * @return
     */
    public static Boolean isWindows() {
        return ShellUtil.getOsName().toLowerCase().contains("win");
    }

    /**
     * 根据系统返回对应平台执行命令
     * @param command
     * @return
     */
    public static ProcessBuilder getProcessBuilder(String command) {
        if (ShellUtil.isWindows()) {
            return new ProcessBuilder("cmd", "/c", command);
        } else {
            return new ProcessBuilder("bash", "-c", command);
        }
    }

    /**
     * 执行系统命令
     * @param command
     * @return
     */
    public static String executeCommand(String command) {
        try {
            ProcessBuilder pb = ShellUtil.getProcessBuilder(command);
            pb.redirectErrorStream(true);

            Process process = pb.start();
            process.waitFor();

            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line);

                // 换行符
                result.append(System.lineSeparator());
            }

            process.waitFor();
            inputStream.close();
            reader.close();

            process.destroy();

            return result.toString();
        } catch (InterruptedException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // System.out.println(ShellUtil.executeCommand("echo 'hello'"));
        // hello

        System.out.println(ShellUtil.executeCommand("python math.py 1 2"));
        // 3
    }
}

参考视频

  1. JAVA开发必会小技巧8——用代码调用系统指令

你可能感兴趣的:(Java学习路线,java,python,开发语言)