(一) Java调用shell方法
public static String ReadCmdLine(String command){
StringBuilder result = new StringBuilder();
Process process = null;
BufferedReader bufrIn = null;
BufferedReader bufrError = null;
try {
process = Runtime.getRuntime().exec(command);
process.waitFor();
//获取执行结果
bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
String line = null;
while ((line = bufrIn.readLine()) != null) {
result.append(line).append('\n');
}
while ((line = bufrError.readLine()) != null) {
result.append(line).append('\n');
}
} catch (Exception e) {
log.error("执行命令失败,e:{}",e);
}finally {
closeStream(bufrIn);
closeStream(bufrError);
// 销毁子进程
if (process != null) {
process.destroy();
}
}
//replaceAll("\\\\x", "%"),解决返回结果编码问题
return result.toString().replaceAll("\\\\x", "%");
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
log.error("关闭连接失败,e:{}");
}
}
}
(二)执行python脚本遇到的问题
- 获取文件路劲不一致:
指令:python console.py –n module_name –a add –f module_file_path;
console.py文件本地是放在项目自建的文件中,由于开发环境是window而服务器环境是Linux,导致路劲错误,无法获取文件。
解决:动态获取项目路劲,采用System.getProperty("user.dir")获取项目根路径;
2.虽然上面的方法解决了获取路径问题,但是有出现一个新的问题,在项目打成tag以后,发布到服务器上时,会在项目中自行添加一层以时间戳命名的文件,结果还是无法获取自定义文件名;
解决:将文件放在项目根目录下,即时间戳的上级目录里;
3.执行含有时间字符串的指令时,时间无法获取;
因为采用的是拼接方式拼成的指令,其他指令都是正常的,偏偏这条指令运行不了,打印出的指令拿过来又可以在shell中运行,问题根源在于拼接的时间字符串因为加了引号,在java编译时出现编码格式问题,导致Java在调用shell执行命令时出错;
解决:将指令存入字符串数组中,让Java编译时自行组合:
new String[]{"python",FilePath,"-n",name,"-a","data","-s",start1,"-e",end1,"-t",way},注意:这里不用添加空格,否则会出错。
此时需要改一下ReadCmdLine方法参数
public static String ReadCmdLine(String[] command){
StringBuilder result = new StringBuilder();
Process process = null;
BufferedReader bufrIn = null;
BufferedReader bufrError = null;
try {
process = Runtime.getRuntime().exec(command);
process.waitFor();
bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
String line = null;
while ((line = bufrIn.readLine()) != null) {
result.append(line).append('\n');
}
while ((line = bufrError.readLine()) != null) {
result.append(line).append('\n');
}
} catch (Exception e) {
log.error("执行命令失败,e:{}",e);
}finally {
closeStream(bufrIn);
closeStream(bufrError);
// 销毁子进程
if (process != null) {
process.destroy();
}
}
return result.toString().replaceAll("\\\\x", "%");
}