How to kill Python interpreter from the command line?

Floris Bruynooghe floris.bruynooghe at gmail.com
Fri May 9 07:41:16 EDT 2008


On May 9, 11:19 am, spectru... at gmail.com wrote:
> Thanks for the replies.
>
> On May 8, 5:50 pm, Jean-Paul Calderone <exar... at divmod.com> wrote:
>
> > Ctrl+C often works with Python, but as with any language, it's possible
> > to write a program which will not respond to it.  You can use Ctrl+\
> > instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored,
> > Ctrl+\ sends SIGQUIT which typically isn't)
>
> Yes, thank you, this seems to work. :)
>
> I did some more testing and found out that the problem seems to be
> thread-related. If I have a single-threaded program, then Ctrl+C
> usually works, but if I have threads, it is usually ignored. For
> instance, the below program does not respond to Ctrl+C (but it does
> die when issued Ctrl+\):
>
> import threading
>
> def loop():
>   while True:
>     pass
>
> threading.Thread(target=loop,args=()).start()

Your thread needs to be daemonised for this work.  Othewise your main
thread will be waiting for your created thread to finish.  E.g.:

thread = threading.Thread(target=loop)
thread.setDaemon(True)
thread.start()

But now it will exit immediately as soon as your main thread has
nothing to do anymore (which is right after .start() in this case), so
plug in another infinite loop at the end of this:

while True:
    time.sleep(10)

And now your threaded app will stop when using C-c.



More information about the Python-list mailing list