【问题标题】:How do I exit() the python script within terminal when I press the 'Escape' key?当我按下“Escape”键时,如何在终端中退出()python脚本?
【发布时间】:2022-01-02 19:58:22
【问题描述】:

这里的目的是在按下转义键后退出脚本,而不必先猜测字母。我认为问题在于 input() 没有将“esc”检测为按键。所以此刻我要猜一个字母,按'enter',然后按'esc'键退出脚本。

def main():  
      import random
      import keyboard
      import sys
       
      # Main program code....
    
      # Keep asking the player until all letters are guessed
      while display != wordChosen:
        guess = input(str("Please enter a guess for the {} ".format(len(display)) + "letter word: "))[0]
        guess = guess.lower()
        #Add the players guess to the list of used letters
        used.extend(guess)
        print ("Attempts: ")
        print (attempts)
        
        while True:
         if keyboard.read_key() == 'esc':
          print("Exiting...")
          sys.exit(0) # this exits your program with exit code 0
        
        # Search through the letters in answer
        for i in range(len(wordChosen)):
          if wordChosen[i] == guess:
            display = display[0:i] + guess + display[i+1:]
    
        print("Used letters: ")
        print(used)
      
        # Search through the letters in answer
    for i in range(len(wordChosen)):
      if wordChosen[i] == guess:
        display = display[0:i] + guess + display[i+1:]
    
    print("Used letters: ")
    print(used)
        
    # Print the string with guessed letters (with spaces in between))
    print(" ".join(display))
        
        # more code....

这是下面的终端输出,我认为问题是让“.guess”的输入()来确认“esc”的键盘按下,但我不知道该怎么做?如您所见,'^[' 被拾取但不会立即退出脚本,除非我按'enter'。抱歉,不知道如何从终端正确粘贴文本。

Please enter a guess for the 5 letter word: ^[
Attempts: 
0
Exiting...
^[%  

【问题讨论】:

标签: python terminal keyboard


【解决方案1】:

您是否在文档中尝试过这种示例:

keyboard.add_hotkey('esc', lambda: exit(0))

【讨论】:

  • @BruceWayne 感谢您的帮助,但是我在 else: break 中添加了因为 while True 循环继续进行导致 input() 函数没有注册字母按键。但是通过添加else: break 'Esc' 不再起作用。这里有语法问题还是我遗漏的其他事情? while True: if keyboard.read_key() == 'esc': print("Exiting...") sys.exit(0) # this exits your program with exit code 0 else: break
猜你喜欢
  • 2015-06-26
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 2014-10-16
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
相关资源
最近更新 更多