本文实现功能: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])))
直接执行文章来源:https://www.toymoban.com/news/detail-620943.html
$ 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
}
}
参考视频文章来源地址https://www.toymoban.com/news/detail-620943.html
- JAVA开发必会小技巧8——用代码调用系统指令
到了这里,关于Java:Java程序通过执行系统命令调用Python脚本的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!