如何在cygwin中运行的python中拦截ctrl + c命令

Cyr*_*Cyr 5 python cygwin python-2.7

我在 cygwin shell 中运行 python 脚本,但无法拦截ctrl+c命令。

这是我的Python脚本:

#!/cygdrive/c/python27/python.exe -u
import signal
import sys
def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGBREAK, signal_handler)

print('Press Ctrl+C')
input()
Run Code Online (Sandbox Code Playgroud)

还使用 try/catch 方法仍然不起作用

#!/cygdrive/c/python27/python.exe -u
try:
    input()
except KeyboardInterrupt:
    print('Interrupted')
Run Code Online (Sandbox Code Playgroud)

但这些处理程序都不能与ctrl+c命令一起使用。Cygwin版本是1.7.25(0.270/5/3),我使用的是python 2.7。怎么了?

Mic*_*pso 1

我在 MSYS 环境(https://www.msys2.org/)的 mingw64 终端中遇到同样的问题。我终于能够使用该winpty工具解决这个问题:

winpty python3 my_python_script.py
Run Code Online (Sandbox Code Playgroud)

这样信号处理程序就可以按预期工作。我只是不确定winpty您的 cygwin 发行版中是否也提供该工具。