在做一个java执行pyhton脚本命令时在网上找了许多方案都不行,最后在stackoverflow上
找到,执行脚本的时候需要带上shell的版本,类似于bash,zsh。看了下服务器上的是zsh,
于是优化代码如下:
java 代码执行linux命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.xiamu.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Description: 调用脚本帮助类
*
* @author haoyuan.yang
* @version 1.0
* @date: 2017/3/10
* @since JDK 1.8
*/
public class PythonUtil {
private static final Logger logger = LoggerFactory.getLogger(PythonUtil.class);
/**
* Description:调用系统命令
*
* @author haoyuan.yang
* @version 1.0
* @date: 2017/3/10 17:55
* @since JDK 1.8
*/
public static void executeCommand(String command) {
try {
Process proc = Runtime.getRuntime()
.exec(new String[] { "zsh", "-c", command });
proc.waitFor();
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
logger.info("execute command {} , result is {}", command, sb.toString());
}
catch (Exception e) {
logger.info("execute command {} fault, e={}", command, e.getMessage());
}
}
}
叔叔,阿姨给点钱买棒棒糖吃