Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I interrupt a blocking method in python?

Usually I can interrupt stuff with Ctrl+C, but sometimes when I'm using threads it doesn't work - example below.

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> time.sleep(100)
^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
K    eyboardInterrupt
>>> import Queue
>>> q = Queue.Queue(maxsize=3)
>>> q.put(0)
>>> q.put(1)
>>> q.put(2)
>>> q.put(3)
^C^C^C^C^C^C^C^C

^C^C^C

^C^C
^C
@*#()#@#@$!!!!!

edit: Is there a way to get back to the interpreter? Solutions so far kill python completely and your existing namespace ..

like image 234
wim Avatar asked Mar 27 '26 00:03

wim


2 Answers

You can kill the Python interpreter with Ctrl+\.

This will send a SIGQUIT instead of SIGINT.

like image 152
phihag Avatar answered Mar 28 '26 13:03

phihag


A quick workaround for ^C failing is suspending the process with all threads first with ^Z and then killing it.

This works in Linux for many cases when ^C fails, and as I've just tested it works here too (tested on Python v.2.6.5):

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Queue
>>> q = Queue.Queue(maxsize=3)
>>> q.put(0)
>>> q.put(1)
>>> q.put(2)
>>> [^C]
KeyboardInterrupt #does not kill the process
>>> [^Z - Suspends and exits to shell]
[1]+  Stopped                 python
#mdf:~$ kill -9 %%
[1]+  Killed                  python
like image 32
flouris Avatar answered Mar 28 '26 12:03

flouris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!