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

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

有正式的方式吗?


当前回答

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

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

其他回答

我想我喜欢这个解决方案:

import getpass
getpass.getpass("Press Enter to Continue")

它隐藏了用户输入的任何内容,这有助于澄清这里没有使用输入。

但是要注意OS X平台。它显示了一个可能令人困惑的键。


最好的解决方案可能是自己执行类似getpass模块的操作,而不执行read -s调用。也许让前景色与背景颜色相匹配?

为了跨Python 2/3兼容性,你可以通过六个库使用输入:

import six
six.moves.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

仅适用于Windows,请使用:

import os
os.system("pause")

这对我来说似乎很好(或Python 2.X中的raw_input())。或者,如果想要暂停特定的秒数,也可以使用time.sleep()。

import time
print("something")
time.sleep(5.5)    # Pause 5.5 seconds
print("something")