Answer the question
In order to leave comments, you need to log in
Why doesn't BufferedReader see EOF?
Hello. I need to read data from stdout for a process running the following
from jupyter_client import MultiKernelManager
mngr = MultiKernelManager()
remote_id = mngr.start_kernel("python3")
print(remote_id)
private Process startProcess(String command) throws Exception {
Process process = Runtime.getRuntime().exec(command);
return process;
}
/** Reads the output stream from the process */
private String readStream(InputStream stream) throws Exception {
InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
StringBuilder response = new StringBuilder();
String[] splitArray;
String msg;
while ((msg = bufferedReader.readLine()) != null) {
logger.debug(msg);
stringBuilder.append(msg).append("\n");
}
logger.debug("Stream was read");
String control = stringBuilder.toString();
splitArray = control.split("\n");
for (String s : splitArray) {
response.append(s).append("\n");
}
bufferedReader.close();
inputStreamReader.close();
String output = response.toString();
output = (output == null || output.length() == 0) ? "" : (output.substring(0, output.length() - 1));
return output;
}
Process process = startProcess(command);
String output = readStream(process.getInputStream());
while ((msg = bufferedReader.readLine()) != null) {
logger.debug(msg);
stringBuilder.append(msg).append("\n");
}
Answer the question
In order to leave comments, you need to log in
The Python process exits before it writes everything to stdout because it uses buffered output by default. To disable this, start the process with the -u flag.
Runtime.getRuntime().exec(new String[] { "python", "-u", "script.py" })
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question