Python 时间 sleep()

在本教程中,我们将了解关于 Python 时间睡眠() 方法. Python 睡眠函数属于早些时候已经讨论的 python 时间模块。

Python 时间睡觉

Python 时间睡眠函数用于添加程序执行的延迟,我们可以使用 Python 睡眠函数在几秒钟内停止该程序的运行,请注意 Python 时间睡眠函数实际上只停止当前线程的执行,而不是整个程序。

Python 时间睡眠() 函数语法

Python sleep() is a method of python time module. So, first we have to import the time module then we can use this method. Way of using python sleep() function is: python time sleep, python sleep Here the argument of the sleep() method t is in seconds. That means, when the statement time.sleep(t) is executed then the next line of code will be executed after t seconds. See the following example:

1# importing time module
2import time
3
4print("Before the sleep statement")
5time.sleep(5)
6print("After the sleep statement")

如果您运行上述代码,那么您将看到第二次打印在5秒后执行,因此您可以根据需要在您的代码中进行延迟。 参数也可以以浮动值进行,以便有更精确的延迟。

1import time
2time.sleep(0.100)

Python 睡眠例子

让我们来看看下面的 Python 时间睡眠函数的例子。

1import time
2startTime = time.time()
3for i in range(0,5):
4   print(i)
5   # making delay for 1 second
6   time.sleep(1)
7endTime = time.time()
8elapsedTime = endTime - startTime
9print("Elapsed Time = %s" % elapsedTime)

这将产生:

10
21
32
43
54
6Elapsed Time = 5.059988975524902

过时时间大于5,因为每次为循环,执行被停止1秒,额外的时间是由于程序的运行时间,操作系统的线程安排等。

Python睡眠的不同延迟时间( )

有时你可能需要延迟不同的秒钟时间,你可以这样做:

1import time
2
3for i in [ .5, .1, 1, 2]:
4   print("Waiting for %s" % i , end='')
5   print(" seconds")
6   time.sleep(i)

这将产生:

1Waiting for 0.5 seconds
2Waiting for 0.1 seconds
3Waiting for 1 seconds
4Waiting for 2 seconds

使用睡眠( )的戏剧性打印

您可能需要以戏剧性的方式打印一些消息,您可以这样做:

1# importing time module
2import time
3message = "Hi!!! I am trying to create suspense"
4
5for i in message:
6   # printing each character of the message
7   print(i)
8   time.sleep(0.3)

如果你运行上述代码,你会看到,在打印消息的每个字符后,它需要一些时间,这看起来像是戏剧性的。

Python 主题 睡眠

Python 时间睡眠() 函数是多线程的非常重要的方法. 下面是一个简单的例子,表明 Python 时间睡眠函数仅在多线程编程中阻止当前线程的执行。

 1import time
 2from threading import Thread
 3
 4class Worker(Thread):
 5    def run(self):
 6        for x in range(0, 11):
 7            print(x)
 8            time.sleep(1)
 9
10class Waiter(Thread):
11    def run(self):
12        for x in range(100, 103):
13            print(x)
14            time.sleep(5)
15
16print("Staring Worker Thread")
17Worker().start()
18print("Starting Waiter Thread")
19Waiter().start()
20print("Done")

Below image shows the output produced by above python thread sleep example. python thread sleep, python time sleep multithreading, python sleep example thread From the output it's very clear that only the threads are being stopped from execution and not the whole program by python time sleep function. That's all about python time sleep function or python sleep function. Reference: StackOverFlow Post, API Doc

Published At
Categories with 技术
Tagged with
comments powered by Disqus