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


当前回答

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

sys.stdin.readline()

其他回答

操作系统。系统似乎总是调用sh,它不识别读取的s和n选项。但是read命令可以传递给bash:

os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")

在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))。

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

sys.stdin.readline()

在Python 3中,使用input():

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

在Python 2中,使用raw_input():

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

简单的使用

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

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

SyntaxError:解析时预期的EOF。

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

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