Python提供了多种方法来设置程序暂停,以便控制程序的执行过程。本文将从多个方面介绍Python设置暂停的方法。
一、使用time模块的sleep函数
time模块是Python标准库中的一个常用模块,提供了与时间相关的函数和方法。其中,sleep函数可以使程序暂停指定的时间。
import time
print("开始执行")
time.sleep(3) # 暂停3秒
print("暂停结束")
上述代码中,使用sleep函数设置了暂停时间为3秒。程序在执行到sleep函数时会暂停3秒,然后继续执行后面的代码。
二、使用sys模块的stdin读取输入
sys模块是Python标准库中的另一个常用模块,提供了与系统相关的功能。可以利用sys.stdin函数实现暂停程序的效果,等待用户输入后再继续执行。
import sys
print("开始执行")
input("按下回车键后继续...")
print("继续执行")
上述代码中,使用input函数等待用户输入,用户按下回车键后,程序会继续执行后面的代码。
三、使用threading模块的Timer类
threading模块是Python标准库中用于多线程编程的模块,其中的Timer类可以在指定时间后执行指定的函数。
import threading
def hello():
print("Hello, world!")
print("开始执行")
timer = threading.Timer(5, hello) # 5秒后执行hello函数
timer.start()
print("继续执行")
上述代码中,使用Timer类创建了一个定时器,定时器在5秒后执行hello函数。程序会在定时器开始后继续执行后面的代码。
四、使用asyncio模块进行协程暂停
asyncio是Python标准库中用于异步编程的模块,可以使用asyncio.sleep函数实现协程的暂停。
import asyncio
async def main():
print("开始执行")
await asyncio.sleep(3) # 暂停3秒
print("暂停结束")
asyncio.run(main())
上述代码中,使用async关键字定义了一个协程函数main。在协程函数中使用await关键字调用了asyncio.sleep函数,实现了3秒的暂停。程序会在暂停期间执行其他协程任务,然后继续执行后面的代码。
五、使用time模块的perf_counter函数计时暂停
time模块中的perf_counter函数可以用于精确计时,可以结合循环和条件语句实现程序的暂停。
import time
print("开始执行")
start_time = time.perf_counter()
while True:
elapsed_time = time.perf_counter() - start_time
if elapsed_time >= 3:
break
print("暂停结束")
上述代码中,使用perf_counter函数获取程序开始执行的时间,然后通过循环计算经过的时间,当经过的时间达到3秒时退出循环,实现了暂停的效果。
原创文章,作者:VSNH,如若转载,请注明出处:https://www.beidandianzhu.com/g/16465.html