我想在我的 Python 脚本中捕获 SIGINT 信号。但是,只有当用户在发送 SIGINT 后输入正确的密码时,脚本才会终止。这可以用 Python 完成吗?一些示例代码来说明问题:
import signal
def signal_handler(signal, frame):
password = raw_input("Enter password: ")
if password != "secret":
print("Wrong password!")
# TODO don't let process end
else:
print("Password correct. Exiting now.")
signal.signal(signal.SIGINT, signal_handler)
编辑:将变量“pass”更改为“password”,如下面评论中的建议。
最佳答案
您可以捕获 SIGINT
并将调用分派(dispatch)给函数。
例如
import signal
import sys
import time
def confirm_password(signal, frame, secret="shhh"):
password = raw_input("Enter password: ")
if password == secret:
sys.exit(0)
else:
print("Password incorrect. Refusing to exit.")
while True:
signal.signal(signal.SIGINT, confirm_password)
time.sleep(1000)
编辑以添加我已经验证可以工作的代码,而不是内存中的示例:)
关于python - 在 Python 中使用条件退出捕获 SIGINT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30760163/