[英]How to request confirmation on program exit?
當用戶嘗試關閉腳本時,我想請求一個純文本密碼。
到目前為止,這是我的代碼,不相關的部分已隱藏。
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:]))
from getpass import getpass
from time import sleep
from os import system, name as os_name
def clear():
system("cls") if os_name == "nt" else system("clear")
def close():
try:
clear()
password = getpass("Please provide authentication password to close the application.")
if password == "admin":
print("Password correct. Closing application now.\n")
exit()
else:
print("Password incorrect. Application continues in 5 seconds.")
sleep(5)
except (KeyboardInterrupt, EOFError):
close()
def loop():
while True:
cmd = input("> ")
if cmd == "close":
close()
else:
print("Hello World!")
def main():
clear()
try:
loop()
except (KeyboardInterrupt, EOFError):
close()
main()
if __name__ == "__main__":
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.