python 如何sleep

原创
admin 2天前 阅读数 3 #Python

Python中可以使用time模块来实现睡眠功能,以下是一个简单的示例:

import time
睡眠5秒钟
time.sleep(5)
输出当前时间
print("Woke up at", time.ctime())

在上面的代码中,我们使用time.sleep()函数让程序睡眠5秒钟,我们使用time.ctime()函数输出当前时间,以验证程序已经睡眠了一段时间。

除了使用time模块外,Python中还有其他库可以实现睡眠功能,比如threading库中的Thread对象,以下是一个使用threading库实现睡眠功能的示例:

import threading
def sleep_for_5_seconds():
    print("Going to sleep...")
    thread = threading.Thread(target=time.sleep, args=(5,))
    thread.start()
    thread.join()
    print("Woke up at", time.ctime())
if __name__ == "__main__":
    sleep_for_5_seconds()

在上面的代码中,我们定义了一个名为sleep_for_5_seconds()的函数,它使用threading库中的Thread对象来创建一个新的线程,并在该线程中调用time.sleep()函数让程序睡眠5秒钟,我们使用thread.join()函数等待线程执行完毕,并输出当前时间以验证程序已经睡眠了一段时间,我们在主函数中调用sleep_for_5_seconds()函数来运行程序。

上一篇:python如何获取 下一篇:python工资如何
热门