views:

190

answers:

4

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
+20  A: 

time.sleep(seconds)

import time

print 1
time.sleep(1)
print 2
time.sleep(0.45)
print 3
time.sleep(3)
print 4
NullUserException
+2  A: 
import time

# ...

time.sleep(1)
Kevin Little
+5  A: 

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 code lines e.g. take 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, you can use sys.settrace to get you own function called before each line is executed and there you can delay, 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.

Anurag Uniyal
+1 With great power...
katrielalex
A: 

I've heard (although can't say for myself) that the whole time.sleep thing isn't a good practice. I was told that threading.Timer was better but that might not do exactly what you want.

See http://stackoverflow.com/questions/391621/compare-using-thread-sleep-and-timer-for-delayed-execution

Ryan Jenkins
The threading.Timer class is for executing a function on a separate thread after a time delay - in that case it is more efficient than starting a thread and sleeping for x seconds. In this case the poster wants to insert delays between statements, so time.sleep is entirely appropriate.
Dave Kirby