Python time.sleep():为代码添加延迟的完整指南
Python time.sleep():为代码添加延迟的完整指南
什么是 Python Sleep?
time.sleep() 函数暂停 Python 脚本执行指定秒数。它属于标准 time 模块,适用于等待外部进程、模拟延迟或单纯延迟输出。
本指南你将学到:
time.sleep()工作原理与语法- 使用
time.sleep()的实战示例 - 延迟函数执行的方法
- 替代延迟方法:
asyncio.sleep()、Event().wait()和Timer
语法
import time # 暂停 seconds 秒 # 示例:time.sleep(5) # 暂停 5 秒
参数
seconds – 浮点数或整数,指示程序暂停多少秒。支持秒的小数部分。
示例:time.sleep() 基础用法
按以下步骤查看延迟效果:
import time- 在需要暂停处添加
time.sleep(5)。
import time
print("Welcome to Python Tutorials")
time.sleep(5)
print("This message appears after a 5-second pause")
输出
Welcome to Python Tutorials This message appears after a 5-second pause
延迟函数调用
有时需要函数运行前延迟。在调用函数前放置 time.sleep():
import time
print('Execution started')
def display():
print('Welcome to Python Tutorials')
time.sleep(5)
display()
print('Function executed with delay')
输出
Execution started Welcome to Python Tutorials Function executed with delay
其他引入延迟的方式
1. 循环中使用 time.sleep()
每字符打印字符串,间隔 1 秒:
import time
message = "Guru99"
for char in message:
print(char)
time.sleep(1)
2. 异步延迟 asyncio.sleep()
Python 3.4+ 可用 asyncio.sleep() 实现非阻塞延迟:
import asyncio
print('Async execution started')
async def display():
await asyncio.sleep(5)
print('Welcome to Python Tutorials')
asyncio.run(display())
3. 线程事件等待
Event().wait() 方法暂停执行指定秒数:
from threading import Event
print('Event wait started')
def display():
print('Welcome to Python Tutorials')
Event().wait(5)
display()
4. 线程定时器
Timer 安排函数延迟运行:
from threading import Timer
print('Timer started')
def display():
print('Welcome to Python Tutorials')
Timer(5, display).start()
核心要点
- 用
time.sleep()精确暂停执行指定时长。 - 异步代码中非阻塞延迟用
asyncio.sleep()。 - 线程工具
Event().wait()和Timer提供替代延迟机制。 - 根据应用并发模型选择最适合的方法。
Python
- Python Lambda匿名函数实战指南
- Python 生成器:高效迭代与进阶用例
- Python 闭包详解:嵌套函数如何捕获变量
- 精通 Python 装饰器:专家技巧增强函数
- Python 轻松获取当前时间与时区数据
- 精通 Python time 模块:函数、结构体与实战示例
- 精通 Python time.sleep():最佳实践、多线程与实战案例
- 精通 Python Lambda 函数:实用示例与最佳实践
- Python round() 函数详解与实战示例
- 精通 Python map() 函数:语法、示例与最佳实践
- Python timeit():精准测量代码执行时间与实战示例
- 精通 Python yield:生成器 vs return 实战指南