Python - 使用“导入信号”处理 CTRL+D

2023-11-23

I can currently handle CTRL+C via:

def hand_inter(signum, frame):
    print 'hey, nice job.'

signal.signal(signal.SIGINT, hand_inter)

However I am required to also handle CTRL+D yet cannot find the appropriate "signal.CTRL+D" call for signum.


Ctrl+D is not a signal, it's end of file.

If you have an interactive program, you will be most probably reading STDIN and Ctrl+D is way how user says that the input is over. Outside this context it does not have any special meaning.

之后执行的代码通常是“readline”或类似调用之后的代码。这相当于读取任何其他文件并检测到它已结束并且没有更多数据可供读取 - 相应的调用将为您提供指示。

例如,这可能是一个简单的交互式程序:

import sys

while True:
    line = sys.stdin.readline()    # readline will return "" on EOF
    if line:
        do_something_with(line)    # * if user just pressed Enter line will
                                   #   be "\n", i.e. still True
    else:                          # * user pressed C-D, i.e. stdin has been
        sys.exit(0)                #   closed readline call must have returned ""

On the other hand, Ctrl+C is different, it's way how user tells their terminal to terminate the running process. It can come at any moment, regardless if the process ever asks for input or even cares about outside world.

因为该过程无法预料到您需要的signal设置所谓的陷阱,这是操作系统提供的启用进程的机制,说:“如果你想终止我,请执行这个......”(这可以是任何东西,包括什么也没有,即只是忽略信号)。异常是像SIGKILL这样的特殊信号,进程无法捕获它们。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python - 使用“导入信号”处理 CTRL+D 的相关文章

随机推荐