我一直在使用输入函数作为暂停脚本的一种方式:
print("something")
wait = input("Press Enter to continue.")
print("something")
有正式的方式吗?
我一直在使用输入函数作为暂停脚本的一种方式:
print("something")
wait = input("Press Enter to continue.")
print("something")
有正式的方式吗?
当前回答
print ("This is how you pause")
input()
其他回答
user12532854建议使用keyboard.readkey(),但它需要特定的键(我试图在没有输入参数的情况下运行它,但它最终立即返回'enter',而不是等待击键)。
通过以不同的方式表达问题(在python中寻找getchar()等效),我发现在探索由这个答案提示的readchar包后,readchar.readkey()做到了这一点。
import readchar
readchar.readkey()
正如mhawke和steveha的评论所指出的,这个问题的最佳答案是:
Python 3. x:
input('Press <ENTER> to continue')
Python 2. x:
raw_input('Press <ENTER> to continue')
For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on Python 2.x) to prompt the user, rather than a time delay. Fast readers won't want to wait for a delay, slow readers might want more time on the delay, someone might be interrupted while reading it and want a lot more time, etc. Also, if someone uses the program a lot, he/she may become used to how it works and not need to even read the long text. It's just friendlier to let the user control how long the block of text is displayed for reading.
轶事:曾经有一段时间,程序使用“按[ANY]键继续”。这个失败了,因为人们抱怨他们在键盘上找不到ANY键:)
我认为停止执行的最好方法是time.sleep()函数。
如果你只需要在某些情况下暂停执行,你可以简单地实现一个If语句,就像这样:
if somethinghappen:
time.sleep(seconds)
您可以让else分支为空。
为了跨Python 2/3兼容性,你可以通过六个库使用输入:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )
非常简单:
raw_input("Press Enter to continue ...")
print("Doing something...")