亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python time.sleep():为代码添加延迟的完整指南

Python time.sleep():为代码添加延迟的完整指南

什么是 Python Sleep?

time.sleep() 函数暂停 Python 脚本执行指定秒数。它属于标准 time 模块,适用于等待外部进程、模拟延迟或单纯延迟输出。

本指南你将学到:

语法

import time
# 暂停 seconds 秒
# 示例:time.sleep(5)  # 暂停 5 秒

参数

seconds – 浮点数或整数,指示程序暂停多少秒。支持秒的小数部分。

示例:time.sleep() 基础用法

按以下步骤查看延迟效果:

  1. import time
  2. 在需要暂停处添加 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()

核心要点

Python

  1. Python Lambda匿名函数实战指南
  2. Python 生成器:高效迭代与进阶用例
  3. Python 闭包详解:嵌套函数如何捕获变量
  4. 精通 Python 装饰器:专家技巧增强函数
  5. Python 轻松获取当前时间与时区数据
  6. 精通 Python time 模块:函数、结构体与实战示例
  7. 精通 Python time.sleep():最佳实践、多线程与实战案例
  8. 精通 Python Lambda 函数:实用示例与最佳实践
  9. Python round() 函数详解与实战示例
  10. 精通 Python map() 函数:语法、示例与最佳实践
  11. Python timeit():精准测量代码执行时间与实战示例
  12. 精通 Python yield:生成器 vs return 实战指南