Python中语句的执行可以延迟吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3327775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:28:17  来源:igfitidea点击:

Can the execution of statements in Python be delayed?

pythonsleepdelaytiming

提问by rectangletangle

I want it to run the first line print 1then wait 1 second to run the second command print 2, etc.

我希望它运行第一行print 1然后等待 1 秒运行第二个命令print 2等。

Pseudo-code:

伪代码:

print 1
wait(1 seconds)
print 2
wait(0.45 seconds)
print 3
wait(3 seconds)
print 4

采纳答案by NullUserException

time.sleep(seconds)

time.sleep(seconds)

import time

print 1
time.sleep(1)
print 2
time.sleep(0.45)
print 3
time.sleep(3)
print 4

回答by Kevin Little

import time

# ...

time.sleep(1)

回答by Anurag Uniyal

All the answers have assumed that you want or can manually insert time.sleepafter each line, but may be you want a automated way to do that for a large number of lines of code e.g. consider this code

所有答案都假设您想要或可以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()

If you want to delay execution of each line, either you can manually insert time.sleepbefore each line which is cumbersome and error-prone, instead you can use sys.settraceto get you own function called before each line is executed and in that callback you can delay execution, so without manually inserting time.sleepat every place and littering code, you can do this instead

如果你想延迟每一行的执行,你可以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()

Without trace output is:

没有跟踪输出是:

1 1280032100.88
2 1280032100.88
func1 1 1280032100.88
func1 2 1280032100.88
func2 1 1280032100.88
func2 2 1280032100.88

With trace output is:

跟踪输出是:

1 1280032131.27
2 1280032132.27
func1 1 1280032134.27
func1 2 1280032135.27
func2 1 1280032137.27
func2 2 1280032138.27

You can further tweak it according to your needs, may be checking line contents too and most importantly this is very easy to disable and will work with any code.

您可以根据自己的需要进一步调整它,也可以检查行内容,最重要的是,这很容易禁用并且可以与任何代码一起使用。