rec*_*gle 15 python sleep timing delay
我希望它运行第一行打印1然后等待1秒以运行第二个命令打印2等.
伪代码:
print 1
wait(1 seconds)
print 2
wait(0.45 seconds)
print 3
wait(3 seconds)
print 4
Run Code Online (Sandbox Code Playgroud)
Nul*_*ion 46
import time
print 1
time.sleep(1)
print 2
time.sleep(0.45)
print 3
time.sleep(3)
print 4
Run Code Online (Sandbox Code Playgroud)
Anu*_*yal 15
所有的答案都假定你想要或者可以time.sleep在每一行之后手动插入,但可能你想要一个自动的方法为大量的代码行做这件事,例如考虑这段代码
def func1():
print "func1 1",time.time()
print "func1 2",time.time()
def func2():
print "func2 1",time.time()
print "func2 2",time.time()
def main():
print 1,time.time()
print 2,time.time()
func1()
func2()
Run Code Online (Sandbox Code Playgroud)
如果你想延迟每一行的执行,要么你可以time.sleep在每一行之前手动插入这很麻烦且容易出错,而是你可以用来sys.settrace在执行每一行之前调用你自己的函数,在那个回调你可以延迟执行,因此,无需手动插入time.sleep每个地方和乱扔垃圾的代码,您可以这样做
import sys
import time
def func1():
print "func1 1",time.time()
print "func1 2",time.time()
def func2():
print "func2 1",time.time()
print "func2 2",time.time()
def main():
print 1,time.time()
print 2,time.time()
func1()
func2()
def mytrace(frame, event, arg):
if event == "line":
time.sleep(1)
return mytrace
sys.settrace(mytrace)
main()
Run Code Online (Sandbox Code Playgroud)
没有跟踪输出是:
1 1280032100.88
2 1280032100.88
func1 1 1280032100.88
func1 2 1280032100.88
func2 1 1280032100.88
func2 2 1280032100.88
Run Code Online (Sandbox Code Playgroud)
跟踪输出是:
1 1280032131.27
2 1280032132.27
func1 1 1280032134.27
func1 2 1280032135.27
func2 1 1280032137.27
func2 2 1280032138.27
Run Code Online (Sandbox Code Playgroud)
您可以根据需要进一步调整它,也可以检查行内容,最重要的是,这很容易禁用,并且可以使用任何代码.