2017-11-18 16 views
0

사용자가 스크립트를 닫으려고 할 때 일반 텍스트 비밀번호를 요청하고 싶습니다.프로그램 종료시 확인 요청 방법?

이것은 지금까지 작성한 코드입니다. 관계없는 부분은 숨겨져 있습니다.

Traceback (most recent call last): 
    File "interface.py", line 96, in <module> 
Preparing to close application. 
Please provide authentication password: 

그리고 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: 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:])) 
+0

라인 67의 파일 interface.py는 무엇을 포함 하는가? 공유 한 코드에는 아무런 문제가 없습니다. 나머지 코드를 다시 확인해야 할 수도 있습니다. – zeeks

+0

신호 처리기를 사용하는 대신 try ... except KeyboardInterrupt :'를 시도합니다. – xaav

+0

@ xaav 당신은 어디에 넣을까요? 그것은 어디든지 갈 수 있습니다. 또한 사용자가 버튼을 두 번 누르는 문제는 해결되지 않습니다. – spikespaz

답변

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() 
+1

실제로 작동합니까? – xaav

+0

그렇지 않습니다. 그것은 빈 역 추적으로 끝납니다. – spikespaz

+0

IPython에서 확인했는데 광고 된대로 작동하는 것 같았습니다. 'guts'와'verifyPassword' 함수는 실제로 이것이 작동하기 위해 무언가를 할 필요가 있음을 주목하십시오. – xaav