如何在程序退出时请求确认?

时间:2017-11-18 21:23:20

标签: python python-3.x signals sigint

我想在用户尝试关闭脚本时请求明文密码。

到目前为止,这是我的代码,隐藏了无关的部分。

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:]))

1 个答案:

答案 0 :(得分: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()