5

Can anyone explain how the interrupt_main() method works in Python?

I've got this piece of Python code :

import time, thread

def f():
    time.sleep(5)
    thread.interrupt_main()

def g():
    thread.start_new_thread(f, ())
    time.sleep(10)
print time.time()
try:
    g()
except KeyboardInterrupt:
    print time.time()

And when I try to run it, it gives me the following output :

1380542215.5
# ... 10 seconds break...
1380542225.51

However, if I interrupt the program manually (CTRL-C), the thread is interrupted correctly :

1380542357.58
^C1380542361.49

Why does the thread interruption only occur after 10 seconds (and not 5) in the first example?

I found an ancient thread n Python mailing list, but it explains nearly nothing.

3
  • KeyboardInterrupt means you are interrupted by a keyboard. Commented Sep 30, 2013 at 12:18
  • Both work as expected. What's your problem? Commented Sep 30, 2013 at 12:23
  • I'd expect the main thread to be interrupted immediately (after 5 seconds). Commented Sep 30, 2013 at 12:25

1 Answer 1

7

raise KeyboardInterrupt does not interrupt a time.sleep(). The former is handled entirely inside the python interpreter, the latter invokes an operating system function.

So, in your case, the keyboard interrupt was handled, but only when time.sleep() completed its system call.

Try this instead:

def g():
    thread.start_new_thread(f, ())
    for _ in range(10): 
        time.sleep(1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.