how to set timeout for os.popen
Jugurtha Hadjar
jugurtha.hadjar at gmail.com
Mon Apr 16 09:33:54 EDT 2018
On 04/15/2018 12:01 PM, Ho Yeung Lee wrote:
> while 1:
> runner = os.popen("tracert -d www.hello.com")
> o=runner.read()
> print(o)
> runner.close()
> runner = os.popen("tracert -d www.hello.com")
> o=runner.read()
> print(o)
> runner.close()
> runner = os.popen("tracert -d www.hello.com")
> o=runner.read()
> print(o)
> runner.close()
>
>
> after running over 1 hour, it stop and not return in one of tracert
>
> how to set timeout and know that this is timeout?
import signal
import time
from contextlib import contextmanager
@contextmanager
def timeout(duration, handler):
"""Timeout after `duration` seconds."""
signal.signal(signal.SIGALRM, handler)
signal.alarm(duration)
try:
yield
finally:
signal.alarm(0)
def interrupt_handler(signum, frame):
print('Interrupt handler saves the day')
raise TimeoutError
# You can use that in many ways:
# At definition time:
@timeout(10, interrupt_handler)
def foo():
print('Begin foo')
while True:
print('foo is printing')
time.sleep(3)
# At use time, define foo normally:
def bar():
print('Begin bar')
while True:
print('bar is printing')
time.sleep(3)
with timeout(10, interrupt_handler):
print('I am inside with, above bar')
bar()
More information about the Python-list
mailing list