Python sleeping without interfering with the script?

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

Such as,

 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.
+4
source share
3 answers

To interpret your description literally, you need to put a print statement before calling func2() .

However, I assume that you really want func2() do a background job that allows func1() to return immediately and not wait for func2() to complete its execution. 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") 
+7
source

You can 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 would 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() 
+5
source

If you are using a command line script, try using the -u option. It runs the script in unbuffered mode and does the trick for me.

For instance:

python -u my_script.py

+3
source

Source: https://habr.com/ru/post/1341555/


All Articles