为SIGTSTP注册信号处理程序在普通的Python解释器中工作。
(py3)$ python
Python 3.4.3 |Continuum Analytics, Inc.| (default, Mar 6 2015, 12:07:41)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import signal
>>> def handler(x, frame):
... print("CAUGHT", x)
...
>>> signal.signal(signal.SIGTSTP, handler)
0
现在我按Ctrl + Z几次,它按预期工作。
>>> CAUGHT 18
CAUGHT 18
CAUGHT 18
但是,在IPython中,它不起作用。调用新的处理程序,但似乎也调用了原始处理程序,并且IPython已停止。
IPython 3.2.0 -- An enhanced Interactive Python.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: def handler(x, frame):
print("CAUGHT", x)
...:
In [2]: import signal
In [3]: signal.signal(signal.SIGTSTP, handler)
Out[3]: 0
现在我点击Ctrl + Z:
In [4]: CAUGHT 18
[2]+ Stopped ipython
顺便说一下,我没有看到Ctrl + C的问题:
In [5]: signal.signal(signal.SIGINT, handler)
Out[5]: <function signal.default_int_handler>
In [6]: CAUGHT 2
IPython使用SIGTSTP做什么?神秘的是,我在IPython 3.2代码库中找不到任何字符串'SIGTSTP'。