我一直在使用输入函数作为暂停脚本的一种方式:
print("something")
wait = input("Press Enter to continue.")
print("something")
有正式的方式吗?
我一直在使用输入函数作为暂停脚本的一种方式:
print("something")
wait = input("Press Enter to continue.")
print("something")
有正式的方式吗?
当前回答
为了跨Python 2/3兼容性,你可以通过六个库使用输入:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )
其他回答
正如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键:)
我有一个类似的问题,我使用信号:
import signal
def signal_handler(signal_number, frame):
print "Proceed ..."
signal.signal(signal.SIGINT, signal_handler)
signal.pause()
因此,您为信号SIGINT注册了一个处理程序,并暂停等待任何信号。现在从你的程序外部(例如在bash中),你可以运行kill -2 <python_pid>,这将向你的python程序发送信号2(即SIGINT)。您的程序将调用已注册的处理程序并继续运行。
我假设您希望在没有输入的情况下暂停。
Use:
time . sleep(秒)
print ("This is how you pause")
input()
我想我喜欢这个解决方案:
import getpass
getpass.getpass("Press Enter to Continue")
它隐藏了用户输入的任何内容,这有助于澄清这里没有使用输入。
但是要注意OS X平台。它显示了一个可能令人困惑的键。
最好的解决方案可能是自己执行类似getpass模块的操作,而不执行read -s调用。也许让前景色与背景颜色相匹配?