背景
项目需要使用Java调用Python实现实体抽取和关系抽取的功能
实现
类
使用ProcessBuilder
类调用命令行
代码
public R<String> test(HttpServletRequest request){
String output = "";
try {
ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "conda activate deepke && " +
"cd C:\\path && " +
"python C:\\path\\test.py");
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
String readLine = "";
while (null != (readLine = br.readLine()))
{
output += readLine;
}
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return R.success(output);
}
坑
- Python脚本中有用到关于路径的
yaml
配置文件,需要注意切换路径 getInputeStream()
方法由于阻塞问题无法读取命令行内容,需要先调用ProcessBuilder.redirectErrorStream(true)
。参考1- 控制台返回的中文乱码问题,
new InputStreamReader
初始化时将编码设置为gbk
待解决的问题
- 调用Python脚本时的路径(暂时在命令行中用
cd
解决) - 其他