首页 > 解决方案 > 为什么真正按 Ctrl-C 键使输入功能忽略以前的输入但 SIGINT 或引发 KeyboardInterrupt 不?

问题描述

可重现的代码:

#!/usr/bin/python3
import time
import os
import signal
try:
    time.sleep(5)
    #raise KeyboardInterrupt or send SIGINT to this program itself
    os.kill(os.getpid(),signal.SIGINT)
except KeyboardInterrupt:
    print("*"+input("e:\n"))

输入一些东西,然后等待 SIGINT 或 KeyboardInterrupt 异常的超时:

$ ./test.py
within timeout
e:
*within timeout

输入一些东西然后立即按下 Ctrl-C 导致一个块等待用户输入并且之前输入的内容被忽略:

$ ./test.py
within timeout
^Ce:
after real Ctrl-C
*after real Ctrl-C

为什么会有这种差异?
我想这与“^C”(文本结尾字符)和处理“^C”控制字符的输入函数的实现有关。
我的猜测正确吗?我也想按需切换这些行为。

标签: pythonlinuxterminalsigint

解决方案


推荐阅读