I have a python script which downloads a text file,reads it line by line and sends the read lines to java. I need to restrict this operation to 5 seconds and receive whatever has been read by the python.
To test whether things are working correctly, I tried this:
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
class ProcessTest {
public static void main(String args[]) {
try {
File file = new File("/home/local/seconds.py");
BufferedReader reader = new BufferedReader(new FileReader(file));
String testCase = "", temp = "";
while ((temp = reader.readLine()) != null) {
testCase = testCase.concat(temp + '\n');
}
reader.close();
ProcessBuilder pb = new ProcessBuilder("python", "-c", testCase);
Process p = pb.start();
if (!p.waitFor(5, TimeUnit.SECONDS)) {
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((temp = reader.readLine()) != null) {
System.out.println(temp);
}
p.destroy();
System.out.println("not ended");
} else {
System.out.println("ended");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
seconds.py file
from time import sleep
for i in range(1,11):
print(i)
sleep(1)
Expected result:
As I have specified the process waitFor
value as 5 seconds, the code should be printing only up to five.
Obtained result: The code executes for more than 5 seconds and it prints up to 10.
How can I set the timeout for a process and print the contents in the buffer?