从Java调用Python脚本时获取输出的问题
我有一个Java程序需要调用一个Python脚本。我使用了exec方法。下面是代码片段:
这个Python程序是用来从维基百科获取一部分文本的,当我单独运行它时,能得到正确的输出。但是当从Java调用它时,我没有得到完整的输出。
我用ready()方法检查了BufferedReader对象的状态(具体可以参考这里),结果代码进入了无限循环。
我觉得其他人也遇到过类似的问题-https://stackoverflow.com/a/20661352/3409074
有人能帮我吗?
public String enhanceData(String name,String entity) {
String s = null;
StringBuffer output = new StringBuffer();
try{
String command="python C://enhancer.py "+name+" "+entity;
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
output.append(s);
}
1 个回答
1
其实,while循环的条件已经读取了一行,所以在每次循环中你实际上是重复读取这一行。
while ((s = stdInput.readLine()) != null) {
//s=stdInput.readLine(); <- don't need this
System.out.println(s);
output.append(s);
}
/Nick