我一直在使用输入函数作为暂停脚本的一种方式:
print("something")
wait = input("Press Enter to continue.")
print("something")
有正式的方式吗?
我一直在使用输入函数作为暂停脚本的一种方式:
print("something")
wait = input("Press Enter to continue.")
print("something")
有正式的方式吗?
当前回答
跨平台的方式;工作无处不在
import os, sys
if sys.platform == 'win32':
os.system('pause')
else:
input('Press any key to continue...')
其他回答
我在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...")
这对我来说似乎很好(或Python 2.X中的raw_input())。或者,如果想要暂停特定的秒数,也可以使用time.sleep()。
import time
print("something")
time.sleep(5.5) # Pause 5.5 seconds
print("something")
我假设您希望在没有输入的情况下暂停。
Use:
time . sleep(秒)
我有一个类似的问题,我使用信号:
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)。您的程序将调用已注册的处理程序并继续运行。
我和喜欢简单解决方案的非程序员一起工作:
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