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


当前回答

你可以使用键盘库:

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

其他回答

你可以使用键盘库:

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

python手册提供了以下内容:

import termios, fcntl, sys, os
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)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", repr(c)
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

它可以滚动到您的用例中。

在Python 3中,使用input():

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

在Python 2中,使用raw_input():

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

如果您想等待输入(这样用户敲击键盘不会导致一些意想不到的事情发生),请使用

sys.stdin.readline()

简单的使用

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

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

SyntaxError:解析时预期的EOF。

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

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