我如何让我的python脚本等待,直到用户按下任何键?


当前回答

在Python 3中,使用input():

input("Press Enter to continue...")

在Python 2中,使用raw_input():

raw_input("Press Enter to continue...")

不过,这只需要等待用户按下enter键。


在Windows/DOS上,可能需要使用msvcrt。msvcrt模块允许你访问Microsoft Visual C/ c++运行时库(msvcrt)中的一些函数:

import msvcrt as m
def wait():
    m.getch()

这应该等待一个按键。


注:

在python3中,raw_input()不存在。 在Python 2中,input(prompt)等价于eval(raw_input(prompt))。

其他回答

如果你想看看他们是否按了一个确切的键(比如“b”),可以这样做:

while True:
    choice = raw_input("> ")

    if choice == 'b' :
        print "You win"
        input("yay")
        break

简单的使用

input("Press Enter to continue...")

将在使用Python 2时导致以下错误:

SyntaxError:解析时预期的EOF。

让代码在Python 2和Python 3上都能工作的简单修复是使用:

try:
    input("Press enter to continue")
except SyntaxError:
    pass

跨平台,Python 2/3代码:

# import sys, os

def wait_key():
    ''' Wait for a key press on the console and return it. '''
    result = None
    if os.name == 'nt':
        import msvcrt
        result = msvcrt.getwch()
    else:
        import termios
        fd = sys.stdin.fileno()

        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)

        try:
            result = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)

    return result

我删除了fctl/非阻塞的东西,因为它给IOErrors,我不需要它。我使用这段代码是因为我想让它阻塞。;)

附录:

我在PyPI上的一个包中实现了这个功能,还有很多其他叫做console的东西:

>>> from console.utils import wait_key

>>> wait_key()
'h'

我是python的新手,我已经在想我太笨了,不能复制这里提出的最简单的建议。 事实证明,我们应该知道一个陷阱:

当从IDLE执行python脚本时,一些io命令的行为似乎完全不同(因为实际上没有终端窗口)。

如。msvcrt。Getch是非阻塞的,总是返回$ff。 这个问题很久以前就已经被报道过了(参见https://bugs.python.org/issue9290)——它被标记为已修复,不知怎么的,这个问题似乎在当前版本的python/IDLE中仍然存在。

因此,如果上面发布的任何代码对您不起作用,请尝试手动运行脚本,而不是从IDLE运行。

你可以使用键盘库:

import keyboard
keyboard.wait('space')
print('space was pressed, continuing...')