8

Hey I need to know how to sleep in Python without interfering with the current script. I've tried using time.sleep() but it makes the entire script sleep.

Like for example


import time
def func1():
    func2()
    print("Do stuff here")
def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()

I want it to immediately print Do stuff here, then wait 10 seconds and print Do more stuff here.

1
  • you need to reorder your statements so they occur in the desired order Commented Feb 27, 2011 at 21:57

3 Answers 3

13

Interpreting your description literally, you need to put the print statement before the call to func2().

However, I'm guessing what you really want is for func2() to a background task that allows func1() to return immediately and not wait for func2() to complete it's execution. In order to do this, you need to create a thread to run func2().

import time
import threading

def func1():
    t = threading.Thread(target=func2)
    t.start()
    print("Do stuff here")
def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()
print("func1 has returned")
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Or another process. Or any other kind of concurrency (coroutines with a hand-written scheduler come to mind, although that's hardly practical).
@delnan: Yes. multiprocessing would be another alternative to provide the same functionality in a different way. If we wanted another impractical solution, I'm sure there is something that involves pigeons that would work.
6

You could use threading.Timer:

from __future__ import print_function
from threading import Timer

def func1():
    func2()
    print("Do stuff here")
def func2():
    Timer(10, print, ["Do more stuff here"]).start()

func1()

But as @unholysampler already pointed out it might be better to just write:

import time

def func1():
    print("Do stuff here")
    func2()

def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()

Comments

3

If you're running your script on command line, try using the -u parameter. It runs the script in unbuffered mode and did the trick for me.

For example:

python -u my_script.py

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.