KeyboardInterrupt

Matthew Barnett mrabarnett at mrabarnett.plus.com
Thu Dec 10 18:10:02 EST 2009


mattia wrote:
> Il Thu, 10 Dec 2009 04:56:33 +0000, Brad Harms ha scritto:
> 
>> On Thu, 10 Dec 2009 00:29:45 +0000, mattia wrote:
>>
>>> Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto:
>>>
>>>> On Dec 9, 11:53 pm, mattia <ger... at gmail.com> wrote:
>>>>> Hi all, can you provide me a simple code snippet to interrupt the
>>>>> execution of my program catching the KeyboardInterrupt signal?
>>>>>
>>>>> Thanks,
>>>>> Mattia
>>>> Errr, normally you can just catch the KeyboardInterrupt exception --
>>>> is that what you mean?
>>>>
>>>> Jon.
>>> Ouch, so the simplest solution is just insert in the 'main' function a
>>> try/catch? I believed there was the necessity to create a signal and
>>> than attach the KeyboardInterrupt to it...
>>
>> KeyboardInterrupt is just an exception that gets raised when CTLR+C (or
>> the OS's equivalent keyboard combo) gets pressed. It can occur at any
>> point in a script since you never know when the user will press it,
>> which is why you put the try: except KeyboardInterrupt: around as much
>> of your script as possible.  The signal that the OS sends to the Python
>> interpreter is irrelevant.
> 
> Ok, so can you tell me why this simple script doesn't work (i.e. I'm not 
> able to catch the keyboard interrupt)?
> 
> import time
> import sys
> from threading import Thread
> 
> def do_work():
>     for _ in range(1000):
>         try:
>             time.sleep(1)
>             print(".", end="")
>             sys.stdout.flush()
>         except KeyboardInterrupt:
>             sys.exit()
> 
> def go():
>     threads = [Thread(target=do_work, args=()) for _ in range(2)]
>     for t in threads:
>         t.start()
>     for t in threads:
>         t.join()
>         
> go()        

Only the main thread can receive the keyboard interrupt.



More information about the Python-list mailing list