嘿,我需要知道如何在不干扰当前脚本的情况下睡在Python中。我尝试过使用 time.sleep(),但它会让整个脚本休眠。
例如
进口时间 def func1(): func2() print(做这里的东西) def func2(): time.sleep(10) print(在这里做更多的事情)func1()
我希望它立即打印在这里做的东西,然后等待10秒钟,然后打印在这里做更多的东西。
解决方案从字面上理解您的描述,您需要在调用 func2() 。
然而,我猜你真正想要的是 func2()到后台任务,它允许 func1()立即返回,而不是等待 func2()来完成它的执行。为此,您需要创建一个线程来运行 func2()。
进口时间进口线程 def func1():t = threading.Thread(target = func2) t.start() print(做这里的东西) def func2(): time.sleep(10) print(在这里做更多的事情) func1() print(func1 has returned)
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.
解决方案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")
更多推荐
Python的睡眠不会干扰脚本?
发布评论