Thread.interrupt_main () does not work while waiting for input

I read about this timeout method blocking I / O operations, the problem is that it does not work. eg:

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 will not 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 does not give me the portability I originally wanted). However, I'm still wondering why the code above does not work.

+6
source share
1 answer

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

Just remove the comma at the end of line 5 or the prompt will not be displayed until the program is completed.

There is a solution for Windows on the same page, but I have not tested it to see if it works.

0
source

Source: https://habr.com/ru/post/917038/


All Articles