Python sleep without interfering with script?

情到浓时终转凉″ 提交于 2019-12-05 10:14:03

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")
jfs

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()

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!