如何在Python中延迟时间?

时间:2022-04-20 20:56:44

I would like to know how to put a time delay in a Python script.

我想知道如何在Python脚本中设置时间延迟。

12 个解决方案

#1


2177  

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

这里还有另外一个例子,它大约每分钟运行一次:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

#2


550  

You can use the sleep() function in the time module. It can take a float argument for sub second resolution.

您可以在time模块中使用sleep()函数。它可以使用浮点数来表示亚秒的分辨率。

from time import sleep
sleep(0.1) # Time in seconds.

#3


116  

Please read https://web.archive.org/web/20090207081238/http://faqts.com/knowledge_base/view.phtml/aid/2609/fid/378, which can help you further:

请阅读https://web.archive.org/web/20090207081238/http:/ faqts.com/knowledge_base/view.phtml/aid/2609/ fid/378可能对您有进一步的帮助:

Try the sleep function in the time module.

在时间模块中尝试睡眠功能。

import time
time.sleep(60)

And put this in a while loop and a statement will only execute on the minute... That allows you to run a statement at predefined intervals regardless of how long the command takes (as long as it takes less than a minute or 5 or 60 or whatever you set it to) For example, I wanted to run a ping once a minute. If I just time.sleep(60) or time.sleep(45) even, the ping will not always take the same amount of time. Here's the code :)

把它放到while循环中,语句只在一分钟内执行……这允许您以预定义的间隔运行语句,而不考虑命令需要多长时间(只要它花费不到一分钟、5分钟或60分钟,或者设置为什么),例如,我希望每分钟运行一次ping。如果我只是时间。sleep(60)或time.sleep(45)甚至,ping不会总是花同样的时间。这是代码:)

time.sleep(time.localtime(time.time())[5])

The [5] just pulls the seconds out of the time.localtime()'s return value.

[5]只是将时间的秒数抽出来。localtime()的返回值。

The great thing about time.sleep is that it supports floating point numbers!

时间的伟大之处。睡眠就是支持浮点数!

import time
time.sleep(0.1) 

http://python.org/doc/current/lib/module-time.html

http://python.org/doc/current/lib/module-time.html

#4


52  

You can get it by simply doing this:

你可以这样做:

from time import sleep

# doing stuff
sleep(0.5) # sleeping half a second (sleep() uses seconds, but you can also use floats)
# doing stuff..

#5


32  

A bit of fun with sleepy generator.

昏昏欲睡的发电机有点乐趣。

The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solutions:

问题是时间延迟。它可以是固定的时间,但是在某些情况下,我们可能需要一个从上次开始计算的延迟。这里有一个可能的解决方案:

Delay measured since last time (waking up regularly)

The situation can be, we want to do something as regularly as possible and we do not want to bother with all the last_time, next_time stuff all around our code.

情况可能是这样的,我们希望尽可能有规律地做一些事情,并且我们不希望在我们的代码中使用所有的last_time、next_time之类的东西。

buzzer generator

Following code (sleepy.py) defines buzzergen gerenarator

下面的代码(sleep .py)定义了buzzergen gerenarator

import time
from itertools import count

def buzzergen(period):
    nexttime = time.time() + period
    for i in count():
        now = time.time()
        tosleep = nexttime - now
        if tosleep > 0:
            time.sleep(tosleep)
            nexttime += period
        else:
            nexttime = now + period
        yield i, nexttime

Invoking regular buzzergen

from sleepy import buzzergen
import time
buzzer = buzzergen(3) # planning to wake up each 3 seconds
print time.time()
buzzer.next()
print time.time()
time.sleep(2)
buzzer.next()
print time.time()
time.sleep(5) # sleeping a bit longer than usually
buzzer.next()
print time.time()
buzzer.next()
print time.time()

and running it we see:

我们可以看到

1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47

We can also use it directly in a loop:

我们也可以直接在循环中使用:

import random
for ring in buzzergen(3):
    print "now", time.time()
    print "ring", ring
    time.sleep(random.choice([0, 2, 4, 6]))

and running it we might see:

我们可以看到

now 1400102751.46
ring (0, 1400102754.461676)
now 1400102754.46
ring (1, 1400102757.461676)
now 1400102757.46
ring (2, 1400102760.461676)
now 1400102760.46
ring (3, 1400102763.461676)
now 1400102766.47
ring (4, 1400102769.47115)
now 1400102769.47
ring (5, 1400102772.47115)
now 1400102772.47
ring (6, 1400102775.47115)
now 1400102775.47
ring (7, 1400102778.47115)

As we see, this buzzer is not too rigid and allow us to catch up regular sleepy intervals even if we oversleep and get out of regular schedule.

正如我们所看到的,这个蜂鸣器不太死板,即使我们睡过头了,也能让我们赶上有规律的睡眠时间。

#6


20  

How can I make a time delay in Python?

In a single thread I suggest the sleep function:

在一个线程我建议睡眠功能:

>>> from time import sleep

>>> sleep(4)

This actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps.

这实际上挂起了操作系统调用的线程的处理,允许其他线程和进程在它休眠时执行。

Use it for that purpose, or simply to delay a function from executing. For example:

为此目的使用它,或者只是为了延迟函数的执行。例如:

>>> def party_time():
...     print('hooray!')
... 
>>> sleep(3); party_time()
hooray!

"hooray!" printed 3 seconds after I hit Enter.

“万岁!”在我按回车键3秒后打印出来。

Example using sleep with multiple threads and processes

Again, sleep suspends your thread - it uses next to zero processing power.

同样,sleep挂起您的线程——它使用几乎为零的处理能力。

To demonstrate, create a script like this (I first attempted this in an interactive Python 3.5 shell, but sub-processes can't find the party_later function for some reason):

为了演示,创建这样的脚本(我首先在交互式的Python 3.5 shell中尝试过,但是由于某些原因,子进程无法找到party_later函数):

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time

def party_later(kind='', n=''):
    sleep(3)
    return kind + n + ' party time!: ' + __name__

def main():
    with ProcessPoolExecutor() as proc_executor:
        with ThreadPoolExecutor() as thread_executor:
            start_time = time()
            proc_future1 = proc_executor.submit(party_later, kind='proc', n='1')
            proc_future2 = proc_executor.submit(party_later, kind='proc', n='2')
            thread_future1 = thread_executor.submit(party_later, kind='thread', n='1')
            thread_future2 = thread_executor.submit(party_later, kind='thread', n='2')
            for f in as_completed([
              proc_future1, proc_future2, thread_future1, thread_future2,]):
                print(f.result())
            end_time = time()
    print('total time to execute four 3-sec functions:', end_time - start_time)

if __name__ == '__main__':
    main()

Example output from this script:

这个脚本的示例输出:

thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037

Multithreading

You can trigger a function to be called at a later time in a separate thread with the Timer threading object:

您可以在一个单独的线程中触发一个函数,该函数将在一个单独的线程中被调用。

>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!

>>> 

The blank line illustrates that the function printed to my standard out and I had to hit Enter to ensure I was on a prompt.

空行显示了打印到我的标准输出的函数,我必须按Enter以确保我在提示符上。

The upside of this method is that while the Timer thread was waiting, I was able to do other things, in this case, hitting Enter one time - before the function executed (see the first empty prompt).

这个方法的好处是,当计时器线程在等待时,我可以做其他事情,在本例中,在执行函数之前(请参见第一个空提示符)按一次Enter。

There isn't a respective object in the multiprocessing library. You can create one, but it probably doesn't exist for a reason. A sub-thread makes a lot more sense for a simple timer than a whole new sub-process.

在多处理库中没有相应的对象。您可以创建一个,但它可能不存在是有原因的。对于一个简单的定时器来说,子线程比一个全新的子进程更有意义。

#7


19  

The tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.

Python标准库中的tkinter库是一个可以导入的交互式工具。基本上,您可以创建按钮、框和弹出窗口以及您使用代码操作的窗口。

If you use tkinter, DO NOT USE TIME.SLEEP() because it will muck up your program. This happened to me. Instead, use root.after() and replace the values for however many seconds, with a milliseconds. E.g, time.sleep(1) is equivalent to root.after(1000) in tkinter.

如果您使用tkinter,不要使用TIME.SLEEP(),因为它会打乱您的程序。这发生在我身上。相反,使用root.after()并将值替换为几秒,使用毫秒。E。睡眠(1)相当于tkinter中的root.after(1000)。

Otherwise, time.sleep(), which many answers have pointed out, which is the way to go.

否则,许多答案都指出,time.sleep()是正确的。

#8


9  

To put a time delay you should import the time module. And with that module you only need to write:

要设置时间延迟,您应该导入时间模块。有了这个模块,你只需要写:

time.sleep(The amount of time)

For example if you want to put a time delay of a second before the computer runs another line you should put:

例如,如果你想在电脑运行另一行之前设置一秒的延时,你应该这样写:

time.sleep(1)
print('Hello World!')

That's all :)

这就是:)

#9


6  

Delays can be implemented by using three methods.

延迟可以通过三种方法实现。

Let's start with the easiest one:

让我们从最简单的开始:

import time
time.sleep(5) #delay for 5 seconds.

Second method to delay would be using the implicit wait method.

延迟的第二个方法是使用隐式等待方法。

 driver.implicitly_wait(5)

Third method is more useful when you have to wait until a particular action is completed or until an element is found.

第三种方法更有用,当您必须等待特定的操作完成或找到一个元素时。

self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))

#10


5  

delays are done with the time library, specifically the time.sleep() function...

时间库会延迟,特别是time.sleep()函数…

To just make it wait for a second:

让它等待一秒钟:

from time import sleep
sleep(1)

This works because by doing:

这是因为:

from time import sleep

you extract the sleep function only from the time library which means you can just call it with:

你只从时间库中提取睡眠功能,这意味着你可以用:

sleep(seconds)

rather than having to type out:

而不是必须打字:

time.sleep()

which is awkwardly long to type.

打字时间很长。

With this method, you wouldn't get access to the other features of the time library and you can't have a variable called sleep. but you could create a variable called time.

使用这个方法,您将无法访问time库的其他特性,也无法拥有名为sleep的变量。但是你可以创建一个变量time。

Doing from [library] import [function] (, [function2]) is great if you just want certain parts of a module.

如果您只想要模块的某些部分,那么从[library]导入[function] (, [function2])是很好的做法。

You could equally do it as:

你同样可以这样做:

import time
time.sleep(1)

and you would have access to the other features of the time library like time.clock() as long as you type time.function but you couldn't create the variable time.

您可以访问time库的其他特性,如time.clock(),只要您输入time。函数,但不能创建变量time。

#11


0  

While everyone else has suggested the de facto, time module, I thought I'd share a different method using matplotlib's pyplot function, pause.

当其他人都建议使用事实上的time模块时,我想我应该使用matplotlib的pyplot函数pause来共享一个不同的方法。

An example

from matplotlib import pyplot as plt
plt.pause(5)    #pauses the program for 5 seconds

Typically this is used to prevent the plot from disappearing as soon as it is plotted or to make crude animations.

通常情况下,这是用来防止情节一旦被绘制出来就消失,或者制作粗糙的动画。

This would save you an import if you already have matplotlib imported.

如果已经导入了matplotlib,那么这将为您保存一个导入。

#12


-9  

Using pygame

使用pygame

import pygame
pygame.init()
while True:
    pygame.time.wait(1000)
    print("This prints every second.")
    print("Please note that this method uses milliseconds.")

#1


2177  

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

这里还有另外一个例子,它大约每分钟运行一次:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

#2


550  

You can use the sleep() function in the time module. It can take a float argument for sub second resolution.

您可以在time模块中使用sleep()函数。它可以使用浮点数来表示亚秒的分辨率。

from time import sleep
sleep(0.1) # Time in seconds.

#3


116  

Please read https://web.archive.org/web/20090207081238/http://faqts.com/knowledge_base/view.phtml/aid/2609/fid/378, which can help you further:

请阅读https://web.archive.org/web/20090207081238/http:/ faqts.com/knowledge_base/view.phtml/aid/2609/ fid/378可能对您有进一步的帮助:

Try the sleep function in the time module.

在时间模块中尝试睡眠功能。

import time
time.sleep(60)

And put this in a while loop and a statement will only execute on the minute... That allows you to run a statement at predefined intervals regardless of how long the command takes (as long as it takes less than a minute or 5 or 60 or whatever you set it to) For example, I wanted to run a ping once a minute. If I just time.sleep(60) or time.sleep(45) even, the ping will not always take the same amount of time. Here's the code :)

把它放到while循环中,语句只在一分钟内执行……这允许您以预定义的间隔运行语句,而不考虑命令需要多长时间(只要它花费不到一分钟、5分钟或60分钟,或者设置为什么),例如,我希望每分钟运行一次ping。如果我只是时间。sleep(60)或time.sleep(45)甚至,ping不会总是花同样的时间。这是代码:)

time.sleep(time.localtime(time.time())[5])

The [5] just pulls the seconds out of the time.localtime()'s return value.

[5]只是将时间的秒数抽出来。localtime()的返回值。

The great thing about time.sleep is that it supports floating point numbers!

时间的伟大之处。睡眠就是支持浮点数!

import time
time.sleep(0.1) 

http://python.org/doc/current/lib/module-time.html

http://python.org/doc/current/lib/module-time.html

#4


52  

You can get it by simply doing this:

你可以这样做:

from time import sleep

# doing stuff
sleep(0.5) # sleeping half a second (sleep() uses seconds, but you can also use floats)
# doing stuff..

#5


32  

A bit of fun with sleepy generator.

昏昏欲睡的发电机有点乐趣。

The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solutions:

问题是时间延迟。它可以是固定的时间,但是在某些情况下,我们可能需要一个从上次开始计算的延迟。这里有一个可能的解决方案:

Delay measured since last time (waking up regularly)

The situation can be, we want to do something as regularly as possible and we do not want to bother with all the last_time, next_time stuff all around our code.

情况可能是这样的,我们希望尽可能有规律地做一些事情,并且我们不希望在我们的代码中使用所有的last_time、next_time之类的东西。

buzzer generator

Following code (sleepy.py) defines buzzergen gerenarator

下面的代码(sleep .py)定义了buzzergen gerenarator

import time
from itertools import count

def buzzergen(period):
    nexttime = time.time() + period
    for i in count():
        now = time.time()
        tosleep = nexttime - now
        if tosleep > 0:
            time.sleep(tosleep)
            nexttime += period
        else:
            nexttime = now + period
        yield i, nexttime

Invoking regular buzzergen

from sleepy import buzzergen
import time
buzzer = buzzergen(3) # planning to wake up each 3 seconds
print time.time()
buzzer.next()
print time.time()
time.sleep(2)
buzzer.next()
print time.time()
time.sleep(5) # sleeping a bit longer than usually
buzzer.next()
print time.time()
buzzer.next()
print time.time()

and running it we see:

我们可以看到

1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47

We can also use it directly in a loop:

我们也可以直接在循环中使用:

import random
for ring in buzzergen(3):
    print "now", time.time()
    print "ring", ring
    time.sleep(random.choice([0, 2, 4, 6]))

and running it we might see:

我们可以看到

now 1400102751.46
ring (0, 1400102754.461676)
now 1400102754.46
ring (1, 1400102757.461676)
now 1400102757.46
ring (2, 1400102760.461676)
now 1400102760.46
ring (3, 1400102763.461676)
now 1400102766.47
ring (4, 1400102769.47115)
now 1400102769.47
ring (5, 1400102772.47115)
now 1400102772.47
ring (6, 1400102775.47115)
now 1400102775.47
ring (7, 1400102778.47115)

As we see, this buzzer is not too rigid and allow us to catch up regular sleepy intervals even if we oversleep and get out of regular schedule.

正如我们所看到的,这个蜂鸣器不太死板,即使我们睡过头了,也能让我们赶上有规律的睡眠时间。

#6


20  

How can I make a time delay in Python?

In a single thread I suggest the sleep function:

在一个线程我建议睡眠功能:

>>> from time import sleep

>>> sleep(4)

This actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps.

这实际上挂起了操作系统调用的线程的处理,允许其他线程和进程在它休眠时执行。

Use it for that purpose, or simply to delay a function from executing. For example:

为此目的使用它,或者只是为了延迟函数的执行。例如:

>>> def party_time():
...     print('hooray!')
... 
>>> sleep(3); party_time()
hooray!

"hooray!" printed 3 seconds after I hit Enter.

“万岁!”在我按回车键3秒后打印出来。

Example using sleep with multiple threads and processes

Again, sleep suspends your thread - it uses next to zero processing power.

同样,sleep挂起您的线程——它使用几乎为零的处理能力。

To demonstrate, create a script like this (I first attempted this in an interactive Python 3.5 shell, but sub-processes can't find the party_later function for some reason):

为了演示,创建这样的脚本(我首先在交互式的Python 3.5 shell中尝试过,但是由于某些原因,子进程无法找到party_later函数):

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time

def party_later(kind='', n=''):
    sleep(3)
    return kind + n + ' party time!: ' + __name__

def main():
    with ProcessPoolExecutor() as proc_executor:
        with ThreadPoolExecutor() as thread_executor:
            start_time = time()
            proc_future1 = proc_executor.submit(party_later, kind='proc', n='1')
            proc_future2 = proc_executor.submit(party_later, kind='proc', n='2')
            thread_future1 = thread_executor.submit(party_later, kind='thread', n='1')
            thread_future2 = thread_executor.submit(party_later, kind='thread', n='2')
            for f in as_completed([
              proc_future1, proc_future2, thread_future1, thread_future2,]):
                print(f.result())
            end_time = time()
    print('total time to execute four 3-sec functions:', end_time - start_time)

if __name__ == '__main__':
    main()

Example output from this script:

这个脚本的示例输出:

thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037

Multithreading

You can trigger a function to be called at a later time in a separate thread with the Timer threading object:

您可以在一个单独的线程中触发一个函数,该函数将在一个单独的线程中被调用。

>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!

>>> 

The blank line illustrates that the function printed to my standard out and I had to hit Enter to ensure I was on a prompt.

空行显示了打印到我的标准输出的函数,我必须按Enter以确保我在提示符上。

The upside of this method is that while the Timer thread was waiting, I was able to do other things, in this case, hitting Enter one time - before the function executed (see the first empty prompt).

这个方法的好处是,当计时器线程在等待时,我可以做其他事情,在本例中,在执行函数之前(请参见第一个空提示符)按一次Enter。

There isn't a respective object in the multiprocessing library. You can create one, but it probably doesn't exist for a reason. A sub-thread makes a lot more sense for a simple timer than a whole new sub-process.

在多处理库中没有相应的对象。您可以创建一个,但它可能不存在是有原因的。对于一个简单的定时器来说,子线程比一个全新的子进程更有意义。

#7


19  

The tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.

Python标准库中的tkinter库是一个可以导入的交互式工具。基本上,您可以创建按钮、框和弹出窗口以及您使用代码操作的窗口。

If you use tkinter, DO NOT USE TIME.SLEEP() because it will muck up your program. This happened to me. Instead, use root.after() and replace the values for however many seconds, with a milliseconds. E.g, time.sleep(1) is equivalent to root.after(1000) in tkinter.

如果您使用tkinter,不要使用TIME.SLEEP(),因为它会打乱您的程序。这发生在我身上。相反,使用root.after()并将值替换为几秒,使用毫秒。E。睡眠(1)相当于tkinter中的root.after(1000)。

Otherwise, time.sleep(), which many answers have pointed out, which is the way to go.

否则,许多答案都指出,time.sleep()是正确的。

#8


9  

To put a time delay you should import the time module. And with that module you only need to write:

要设置时间延迟,您应该导入时间模块。有了这个模块,你只需要写:

time.sleep(The amount of time)

For example if you want to put a time delay of a second before the computer runs another line you should put:

例如,如果你想在电脑运行另一行之前设置一秒的延时,你应该这样写:

time.sleep(1)
print('Hello World!')

That's all :)

这就是:)

#9


6  

Delays can be implemented by using three methods.

延迟可以通过三种方法实现。

Let's start with the easiest one:

让我们从最简单的开始:

import time
time.sleep(5) #delay for 5 seconds.

Second method to delay would be using the implicit wait method.

延迟的第二个方法是使用隐式等待方法。

 driver.implicitly_wait(5)

Third method is more useful when you have to wait until a particular action is completed or until an element is found.

第三种方法更有用,当您必须等待特定的操作完成或找到一个元素时。

self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))

#10


5  

delays are done with the time library, specifically the time.sleep() function...

时间库会延迟,特别是time.sleep()函数…

To just make it wait for a second:

让它等待一秒钟:

from time import sleep
sleep(1)

This works because by doing:

这是因为:

from time import sleep

you extract the sleep function only from the time library which means you can just call it with:

你只从时间库中提取睡眠功能,这意味着你可以用:

sleep(seconds)

rather than having to type out:

而不是必须打字:

time.sleep()

which is awkwardly long to type.

打字时间很长。

With this method, you wouldn't get access to the other features of the time library and you can't have a variable called sleep. but you could create a variable called time.

使用这个方法,您将无法访问time库的其他特性,也无法拥有名为sleep的变量。但是你可以创建一个变量time。

Doing from [library] import [function] (, [function2]) is great if you just want certain parts of a module.

如果您只想要模块的某些部分,那么从[library]导入[function] (, [function2])是很好的做法。

You could equally do it as:

你同样可以这样做:

import time
time.sleep(1)

and you would have access to the other features of the time library like time.clock() as long as you type time.function but you couldn't create the variable time.

您可以访问time库的其他特性,如time.clock(),只要您输入time。函数,但不能创建变量time。

#11


0  

While everyone else has suggested the de facto, time module, I thought I'd share a different method using matplotlib's pyplot function, pause.

当其他人都建议使用事实上的time模块时,我想我应该使用matplotlib的pyplot函数pause来共享一个不同的方法。

An example

from matplotlib import pyplot as plt
plt.pause(5)    #pauses the program for 5 seconds

Typically this is used to prevent the plot from disappearing as soon as it is plotted or to make crude animations.

通常情况下,这是用来防止情节一旦被绘制出来就消失,或者制作粗糙的动画。

This would save you an import if you already have matplotlib imported.

如果已经导入了matplotlib,那么这将为您保存一个导入。

#12


-9  

Using pygame

使用pygame

import pygame
pygame.init()
while True:
    pygame.time.wait(1000)
    print("This prints every second.")
    print("Please note that this method uses milliseconds.")