Python Forum

Full Version: printing contents of Jar on timeout
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have a requirement to execute a jar, and also have a timeout mechanism around it , such that when a timeout occurs, the exeuction stops.

On my research I found that we can use the 'timeout' attribute of subprocess.call()

To replicate my usecase, I have a jar which prints a message every second for 15 seconds.
Now the python application is coded as below.

import subprocess
X1 = subprocess.run(['java', '-jar', 'JarsForPython2.jar'],timeout=15)
print('------------checks for stdout-----------------------')
print(X1.stdout.decode())
print('------------checks for stderr-----------------------')
print(X1.stdout.decode())
Everything works smooth. Now to check for the timeout, I make the changes and set timeout=7
I modify the code and handle the exception as below.

try:
    X1 = subprocess.run(['java', '-jar', 'JarsForPython2.jar'], capture_output=True, timeout=7.0)
except subprocess.TimeoutExpired as e:
    print('The execution has timedout')
else:
    print('------------checks for stdout-----------------------')
    print(X1.stdout.decode())
    print('------------checks for stderr-----------------------')
    print(X1.stderr.decode())
Now here, I get

Error:
The execution has timedout Process finished with exit code 0
I just want to have the output of the first six seconds log here on my console.
Any suggestion?
if I get what you want, try

try:
    X1 = subprocess.run(['java', '-jar', 'JarsForPython2.jar'], capture_output=True, timeout=7.0)
except subprocess.TimeoutExpired as e:
    print('The execution has timedout')
finally:
    print('------------checks for stdout-----------------------')
    print(X1.stdout.decode())
    print('------------checks for stderr-----------------------')
    print(X1.stderr.decode())