Python睡眠而不干扰脚本?
嘿,我想知道在Python中怎么让程序暂停一下,但又不影响当前的脚本运行。我试过用 time.sleep()
,但这样会让整个脚本都暂停。
比如说,像这样
import time
def func1():
func2()
print("Do stuff here")
def func2():
time.sleep(10)
print("Do more stuff here")
func1()
我希望它能立刻打印“在这里做点事情”,然后等10秒再打印“在这里做更多事情”。
3 个回答
3
如果你是在命令行上运行你的脚本,可以试试加上 -u
这个参数。这个参数会让脚本以“无缓冲”的模式运行,对我来说效果很好。
比如说,你可以这样写:
python -u my_script.py
6
你可以使用 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()
但是正如 @unholysampler 已经指出的,其实直接写下面的代码可能更好:
import time
def func1():
print("Do stuff here")
func2()
def func2():
time.sleep(10)
print("Do more stuff here")
func1()
13
根据你描述的意思,你需要把打印语句放在调用 func2()
之前。
不过,我猜你真正想要的是让 func2()
在后台运行,这样 func1()
就可以立刻返回,而不需要等 func2()
完成。为了做到这一点,你需要创建一个线程来运行 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")