Python sleep()函数会将延迟代码的执行。 sleep()是time模块的一部分。
import time
time.sleep(seconds)
参数:
seconds:您希望停止执行代码的秒数。
第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秒后才会打印出来
示例
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
使用sleep()函数
import time
my_message = "Guru99"
for i in my_message:
print(i)
time.sleep(1)
输出
G
u
r
u
9
9
asyncio.sleep异步线程函数中延时(Python 3.4或更高版本)
您可以在python 3.4及更高版本中使用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
使用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
使用计时器
计时器是线程处理中可用的另一种方法,它有助于获得与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