当用户试图关闭脚本时,我想请求一个明文密码。
这是我到目前为止的代码,不相关的部分是隐藏的。
import signal
from time import sleep
_password = "iAmAdmin"
def _close(args):
"""Close the application."""
if input("Preparing to close application.\n"
"Please provide authentication password: ") == _password:
print("Password correct. Application closing.")
exit()
else:
print("Invalid password. Program will continue in 5 seconds.")
sleep(5)
# Signal handler.
def sighandler(sig, frame):
_close(None)
# Initiate the interface.
if __name__ == "__main__":
signal.signal(signal.SIGINT, sighandler)
clear() # Function to clear the terminal.
start() # Display beginning help message.
loop() # An infinite loop requesting input and running functions.
CTRL+C
按下,结果如下:
Traceback (most recent call last):
File "interface.py", line 96, in <module>
Preparing to close application.
Please provide authentication password:
如果
SIGINT
在此期间再次发送,它会自动关闭。在用户输入正确的密码之前,应该忽略该选项。
如果用户键入了正确的密码,应用程序将崩溃:
Traceback (most recent call last):
File "interface.py", line 96, in <module>
Preparing to close application.
Please provide authentication password: password
Invalid password. Program will continue in 5 seconds.
loop()
File "interface.py", line 67, in loop
cmd = input(_prompt)
EOFError
很明显,我遗漏了一些东西。这是怎么一回事?
编辑:
根据要求,以下是
loop()
函数(包含第67行)。
# All interface functionality below.
def loop():
"""Infinite loop that handles all interface commands."""
while True:
cmd = input(_prompt) # Line 67.
cmd, args = cmd.lower().split(" ", 1) if " " in cmd else (cmd, None)
if cmd == "help":
_help(cmds, args)
elif cmd in cmds:
cmds[cmd](args)
else:
print("Unrecognized command:", cmd, "\nType \"help\" for a list of commands.")
suggestions = _suggest(cmds, cmd)
if suggestions:
print("\nDid you mean \"" + suggestions[0] + "\"?")
if len(suggestions) > 1:
print("Similar commands:", ", ".join(suggestions[-1:]))