gpt4 book ai didi

Python 在不干扰脚本的情况下休眠?

转载 作者:太空狗 更新时间:2023-10-30 00:25:37 25 4
gpt4 key购买 nike

嘿,我需要知道如何在不干扰当前脚本的情况下在 Python 中休眠。我试过使用 time.sleep() 但它会使整个脚本进入休眠状态。

比如


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

<p>func1()
</p>
我希望它立即打印 Do stuff here,然后等待 10 秒并打印 Do more stuff here。

最佳答案

从字面上解释您的描述,您需要在调用 func2() 之前放置 print 语句。

不过,我猜你真正想要的是让 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")

关于Python 在不干扰脚本的情况下休眠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5136266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com