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

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

有正式的方式吗?


当前回答

非常简单:

raw_input("Press Enter to continue ...")
print("Doing something...")

其他回答

我在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...")
print ("This is how you pause")

input()

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

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

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

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


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

非常简单:

raw_input("Press Enter to continue ...")
print("Doing something...")

我和喜欢简单解决方案的非程序员一起工作:

import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals()) 

这产生了一个几乎完全像真正的解释器一样的解释器,包括当前上下文,只有输出:

Paused. Press ^D (Ctrl+D) to continue.
>>>

Python调试器也是暂停的好方法。

import pdb
pdb.set_trace() # Python 2

or

breakpoint() # Python 3