我一直在使用输入功能来暂停我的脚本
print("something")
wait = input("PRESS ENTER TO CONTINUE.")
print("something")
有正式的方法吗?
答案 0 :(得分:187)
对我来说似乎很好(或者在Python 2.X中为raw_input()
)。或者,如果您想暂停一定的秒数,可以使用time.sleep()
。
import time
print("something")
time.sleep(5.5) # pause 5.5 seconds
print("something")
答案 1 :(得分:22)
使用:
import os
os.system("pause")
答案 2 :(得分:19)
答案 3 :(得分:12)
所以,我发现这在我的编码工作中非常有效。我只是在程序的最开始创建了一个函数,
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
答案 4 :(得分:7)
我有一个类似的问题,我正在使用信号:
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)。您的程序将调用您的注册处理程序并继续运行。
答案 5 :(得分:7)
我使用以下python
2和3来暂停代码执行,直到用户按下 ENTER
import six
if six.PY2:
raw_input("Press the <ENTER> key to continue...")
else:
input("Press the <ENTER> key to continue...")
答案 6 :(得分:6)
很简单:
raw_input("Press Enter to continue ...")
exit()
答案 7 :(得分:5)
Print ("This is how you pause")
input()
答案 8 :(得分:4)
正如mhawke和steveha所述,这个问题的最佳答案是:
对于长文本块,最好使用
input('Press <ENTER> to continue')
(或raw_input('Press <ENTER> to continue')
Python 2.x)提示用户,而不是时间延迟。读者快 不想等待延迟,慢读者可能想要更多时间 延迟,有人可能会在阅读时被打断并想要一个 更多的时间等等。此外,如果有人使用该程序很多,他/她 可能会习惯它的工作方式,甚至不需要读长篇 文本。让用户控制块多长时间更友好 显示文本以供阅读。
答案 9 :(得分:1)
通过这种方法,您只需按指定的任何指定键即可恢复程序:
import keyboard
while True:
key = keyboard.read_key()
if key == 'space': # You can put any key you like instead of 'space'
break
相同的方法,但是以另一种方式:
import keyboard
while True:
if keyboard.is_pressed('space'): # The same. you can put any key you like instead of 'space'
break
注意:您只需在shell或cmd中编写此模块即可安装keyboard
模块:
pip install keyboard
答案 10 :(得分:1)
跨平台方式;随处可见
import os, sys
if sys.platform == 'win32':
os.system('pause')
else:
input('Press any key to continue...')
答案 11 :(得分:0)
我认为停止执行的最佳方法是time.sleep()函数。 如果你只需要在某些情况下暂停执行,你可以简单地实现这样的if语句:
array_agg
你可以将else分支留空。
答案 12 :(得分:0)
我想我喜欢这种饮料。
import getpass
getpass.getpass("Press Enter to Continue")
它隐藏了用户键入的任何内容,这有助于弄清此处未使用输入。
但是请注意,在OSX平台上,它显示的密钥可能会引起混淆。
最好的解决方案可能是自己进行类似于getpass模块的操作,而无需进行read -s
调用。也许让fg颜色与bg匹配?
答案 13 :(得分:0)
要获得跨Python 2/3的兼容性,可以通过"@year"
库使用input
:
six
答案 14 :(得分:0)
我与喜欢简单解决方案的非程序员合作:
import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())
这将产生一个解释器,其行为几乎与真正的解释器(包括当前上下文)完全一样,仅具有输出:
Paused. Press ^D (Ctrl+D) to continue. >>>
Python Debugger也是暂停的好方法。
import pdb
pdb.set_trace() # Python 2
或
breakpoint() # Python 3