I've read about this technique to timeout blocking IO operations, the problem is that it doesn't seem to work. for example:
import thread, threading
def read_timeout(prompt, timeout=10.0):
timer = threading.Timer(timeout, thread.interrupt_main)
s = ''
timer.start()
try:
s = raw_input(prompt)
except KeyboardInterrupt:
print 'operation timed out.'
timer.cancel()
return s
s = read_timeout('enter input: ')
if s:
print 'you entered: %s' % s
this won't interrupt the main thread until raw_input() returns.
Any help is appreciated.
Using os.kill(os.getpid(), signal.SIGINT) instead of thread.interrupt_main() seems to work (at least on Linux, which doesn't give me the portability I initially wanted). However, I'm still wondering why the code above doesn't work.
According to the latest doc of the API: https://docs.python.org/3/library/_thread.html#thread.interrupt_main
This does not emit the corresponding signal but schedules a call to the associated handler (if it exists).
And the call is performed after the current blocking call in the main thread.
On the other hand, the os.kill solution mentioned in the update immediately emits a signal to the main thread.
Sorry that it's been quite a while since the question was raised, but hopefully it still helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With