【问题标题】:How to quit python2.x script when ESCape is pressed [duplicate]按下ESCape时如何退出python2.x脚本[重复]
【发布时间】:2015-06-26 17:54:54
【问题描述】:

我是 python 新手,我有一个 python2.x 脚本,要求用户在 bash 中选择答案 A、B 或 C。在等待用户输入的同时仅按下转义键时,如何使脚本立即退出?

目前,我有这个功能。但是,在退出键后我也必须按回车。

def choice(prompt):
    """
    Choose A, B or C
    ESC exits script
    """
    while True:
        char = raw_input(prompt)
        if char.encode() == '\x1B': # ESC is pressed
            sys.exit("Quitting ...")
        elif char.lower() not in ('a', 'b', 'c'):
            print("Wrong input. Please try again.")
            continue
        else:
            break
    return char

user_choice = choice("\nChoose between A - C: ")
print("You chose %s.") % user_choice.upper()

代码是 UTF-8 格式,bash 终端中的转义键给了我 ^[。据我了解 msvcrt 在 Linux 中不起作用。可以这样做,所以脚本可以在 Windows 和 Linux 中运行吗?

【问题讨论】:

  • 你可以使用curses模块docs.python.org/3/library/curses.html
  • curses (尽可能)独立于操作系统,并为Windows 对象提供getch() 函数。它返回单次击键,无论是否等待,甚至是 ESC 或 CTRL-x。您可以抑制 Ctrl-Break 功能等。该包称为 ncurses。
  • @HansThen 谢谢,这解决了我的问题。我添加了这些类,然后 getch = _Getch() char = getch.impl()
  • @HansThen 如何识别是否按下了回车键?我用 u'001b' 覆盖了 ESC,但不知道输入的 unicode(如果有的话)?

标签: python linux bash escaping


【解决方案1】:

要阅读和输入而无需用户按回车,您可以使用msvcrt 模块。你可以找到更多关于它的信息here

【讨论】:

  • 感谢您的回答,但 bash 是 Linux 终端,我认为 'msvcrt' 仅适用于 Windows/DOS。
猜你喜欢
  • 1970-01-01
  • 2015-11-15
  • 2019-07-05
  • 2011-01-22
  • 2023-03-29
  • 2016-03-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
相关资源
最近更新 更多