愉快的国庆假期结束啦,补一篇博客。
参考文档:
- java调用python脚本
- Java调用shell脚本
环境
- Python 3.8.6 位于Linux服务器中
param为调用脚本需要传入的参数,参数之间使用空格隔开进行组装。
Java代码:
public Integer executeShell(String param){
String cmdStr = "bash /opt/apps/test.sh"+" "+param;
byte[] buffer = new byte[1024];
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ByteArrayOutputStream outErrStream = new ByteArrayOutputStream();
try {
Process proc = Runtime.getRuntime().exec(cmdStr);
InputStream errStream = proc.getErrorStream();
InputStream stream = proc.getInputStream();
// 流读取与写入
int len = -1;
while ((len = errStream.read(buffer)) != -1) {
outErrStream.write(buffer, 0, len);
}
while ((len = stream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
int resultCode = proc.waitFor();// 等待命令执行完成
return resultCode;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
2.改进
与上述参考资料中直接调用Python脚本不同,因为Linux服务器上的Python是通过MiniConda安装的,详见我之前的博客Linux服务器上部署conda。我需要先激活Conda虚拟环境才能调用Python脚本。
所以我通过Java调用shell脚本,在shell脚本中调用Python脚本。传递的参数使用$1、$2...来接收
改进后的Shell代码:
#!/bin/sh # 激活虚拟环境 source /root/miniconda3/bin/activate Myenv # 调用Python脚本进行数据分析 python /opt/apps/pythonapps/test.py "$1" "$2" "$3" "$4"
努力,进取,奋斗!



