7

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.

Update:

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.

Community
  • 1
  • 1
Amr
  • 695
  • 4
  • 11

2 Answers2

0

On Unix machines, there is a way to do what you are trying to do. Look at this post: raw_input and timeout

Just remove the comma at the end of line 5, or the prompt won't be displayed until the program is terminated.

On the same page there's also solution for Windows OS, but I haven't tested it to know if it's working.

Community
  • 1
  • 1
Kiet Tran
  • 1,458
  • 2
  • 13
  • 22
  • I know about select, but I was looking for something portable :) also the main reason I posted the question is because I wanted to know what's wrong with my code. – Amr May 30 '12 at 20:37
0

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 contrary, the os.kill solution mentioned in the update actually 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.

caocao
  • 1