什么是Python Sleep?
Python sleep()函数会将延迟代码的执行。 sleep()是time模块的一部分。
语法
import time
time.sleep(seconds)
参数:
seconds:您希望停止执行代码的秒数。
示例:在Python中使用sleep()函数
第1步:
import time
步骤2:
time.sleep(5)
import time
print("Welcome to guru99 Python Tutorials")
time.sleep(5)
print("This message will be printed after a wait of 5 seconds")
输出
Welcome to guru99 Python Tutorials
This message will be printed after a wait of 5 seconds#因为延时,这一行在5秒后才会打印出来
如何使用sleep()延迟执行功能?
示例
import time
print('Code Execution Started')
def display():
print('Welcome to Guru99 Tutorials')
time.sleep(5)
display()
print('Function Execution Delayed')
输出
Code Execution Started
Welcome to Guru99 Tutorials
Function Execution Delayed
- display()函数将显示一条消息“ Welcome to Guru99 Tutorials”。 sleep()将在此处暂停指定的秒数,稍后将结束执行display()函数,并打印'Function Execution Delayed'。
在Python脚本中添加延迟有哪些不同的方法?
使用sleep()函数
import time
my_message = "Guru99"
for i in my_message:
print(i)
time.sleep(1)
输出
G
u
r
u
asyncio.sleep异步线程函数中延时(Python 或更高版本)
您可以在python 及更高版本中使用asyncio.sleep。
如下例所示:
import asyncio
print('Code Execution Started')
async def display():
await asyncio.sleep(5)
print('Welcome to Guru99 Tutorials')
asyncio.run(display())
Output:
Code Execution Started
Welcome to Guru99 Tutorials
- asyncio.run开始一个新线程来异步执行display()函数
- 函数display(),它显示一条消息“ Welcome to Guru99 tutorials”。 async和await是两个关键字。 在函数定义的开头添加async关键字,并在asyncio.sleep()之前添加await。 关键字async / await均用于处理异步任务。
- 当调用函数display()并遇到asyncio.sleep(5)时,代码将在该点处睡眠或暂停5秒钟,完成后将打印该消息。
使用Event().wait(一般用于多线程)
Event().wait方法来自线程模块。 Event.wait()方法将停止任何进程的执行,等待指定的秒数:
from threading import Event
print('Code Execution Started')
def display():
print('Welcome to Guru99 Tutorials')
Event().wait(5)
display()
输出
Code Execution Started
Welcome to Guru99 Tutorials
- 该代码使用Event().wait(5)。 5秒钟后,将调用函数display(),并将消息打印在终端内部。
使用计时器
计时器是线程处理中可用的另一种方法,它有助于获得与sleep相同的功能。
from threading import Timer
print('Code Execution Started')
def display():
print('Welcome to Guru99 Tutorials')
t = Timer(5, display)
t.start()
输出
Code Execution Started
Welcome to Guru99 Tutorials
- 计时器的参数包括延迟的时间(以秒为单位)以及时钟到时,需要执行的任务。 要使计时器正常工作,您需要调用start()方法。 在代码中Timer 第一个参数是5秒,5秒后会调用display函数。 当调用t.start()时,计时器将开始工作。