如何在Python中中断一个阻塞方法?
通常我可以通过按Ctrl+C来中断正在运行的程序,但有时候在使用线程的时候,这个方法就不管用了 - 下面是一个例子。
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
@*#()#@#@$!!!!!
补充:有没有办法回到解释器?目前的解决方案都是直接杀掉Python程序,这样会导致你之前的工作空间也消失了……
3 个回答
0
一种简单的方法就是打开另一个窗口。
先输入 ps
来查看进程的ID。
然后用 kill
命令来结束那个有问题的进程。
1
一个快速的解决办法,当按下 ^C 不能终止程序时,可以先用 ^Z 暂停这个程序及其所有线程,然后再将其杀掉。
在很多情况下,这个方法在 Linux 系统上有效,当 ^C 失效时可以尝试这个方法。我刚刚测试过,在 Python 版本 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
3
你可以通过按 Ctrl + \ 来结束 Python 解释器。
这样做会发送一个 SIGQUIT
信号,而不是 SIGINT
信号。