我一直在使用输入函数作为暂停脚本的一种方式:

print("something")
wait = input("Press Enter to continue.")
print("something")

有正式的方式吗?


当前回答

user12532854建议使用keyboard.readkey(),但它需要特定的键(我试图在没有输入参数的情况下运行它,但它最终立即返回'enter',而不是等待击键)。

通过以不同的方式表达问题(在python中寻找getchar()等效),我发现在探索由这个答案提示的readchar包后,readchar.readkey()做到了这一点。

import readchar
readchar.readkey()

其他回答

print ("This is how you pause")

input()

user12532854建议使用keyboard.readkey(),但它需要特定的键(我试图在没有输入参数的情况下运行它,但它最终立即返回'enter',而不是等待击键)。

通过以不同的方式表达问题(在python中寻找getchar()等效),我发现在探索由这个答案提示的readchar包后,readchar.readkey()做到了这一点。

import readchar
readchar.readkey()

我假设您希望在没有输入的情况下暂停。

Use:

time . sleep(秒)

我在Python 2和Python 3中使用以下代码暂停代码执行,直到用户按下Enter

import six

if six.PY2:
    raw_input("Press the <Enter> key to continue...")
else:
    input("Press the <Enter> key to continue...")

所以,我发现这在我的编程工作中非常有效。我只是在程序的最开始创建了一个函数,

def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

现在我可以在任何需要的时候使用pause()函数,就像我在写一个批处理文件一样。例如,在这样的程序中:

import os
import system

def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

print("Think about what you ate for dinner last night...")
pause()

很明显,这个项目没有目标,只是举个例子,但你可以准确地理解我的意思。

注意:对于Python 3,你需要使用input而不是raw_input