开发者

How can I interrupt a blocking method in python?

开发者 https://www.devze.com 2023-04-02 11:22 出处:网络
U开发者_如何学Csually I can interrupt stuff with Ctrl+C, but sometimes when I\'m using threads it doesn\'t work - example below.

U开发者_如何学Csually 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 ..


You can kill the Python interpreter with Ctrl+\.

This will send a SIGQUIT instead of SIGINT.


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


A lazy way to do this is to open another window.

Do ps to get the PID.

Do kill to kill the offending process.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号