Can the execution of statements in Python be delayed?

26,343

Solution 1

time.sleep(seconds)

import time

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

Solution 2

All the answers have assumed that you want or can manually insert time.sleep after 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

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.sleep before each line which is cumbersome and error-prone, instead you can use sys.settrace to get you own function called before each line is executed and in that callback you can delay execution, so without manually inserting time.sleep at every place and littering code, you can do this instead

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.

Solution 3

import time

# ...

time.sleep(1)
Share:
26,343
rectangletangle
Author by

rectangletangle

Updated on July 11, 2020

Comments

  • rectangletangle
    rectangletangle almost 4 years

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

    Pseudo-code:

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