sleep()在python 3和python 2的time()模块中定义
有时,需要破坏程序的流程,以便可以进行其他几次执行,或者仅仅是由于所需的实用程序。 sleep()在这种情况下可以派上用场,这种情况提供了一种精确灵活的方式来在任何时间段内破坏代码流。此功能讨论此功能的见解。
Syntax:sleep(sec)
参数:
sec: Number of seconds for which the code is required to be stopped.
返回: VOID.
代码1:演示sleep()
# Python code to demonstrate
# working of sleep()
import time
# printing the start time
print("The time of code execution begin is:", end ="")
print(time.ctime())
# using sleep() to hault the code execution
time.sleep(6)
# printing the end time
print("The time of code execution end is:", end ="")
print(time.ctime())
输出:
The time of code execution begin is:Mon Apr 9 20:57:10 2018
The time of code execution end is:Mon Apr 9 20:57:16 2018
应用:
sleep()用于许多应用程序。如果以固定间隔重复执行后台线程,则可以借助sleep()来实现。另一个流行的应用程序是使用sleep()逐个字母打印单词,以获得良好的用户界面。后者由下面的代码表示。
代码2:演示sleep()的应用
# Python code to demonstrate
# application of sleep()
import time
# initializing string
strn = "GeeksforGeeks"
# printing geeksforgeeks after delay
# of each character
for i in range(0, len(strn)):
print(strn[i], end ="")
time.sleep(2)
输出:
GeeksforGeeks
注意:sleep()的可见效果可以在本地编辑器中看到。