如何延迟时间?

发布于 2024-07-12 09:34:23 字数 28 浏览 12 评论 0原文

如何在 Python 脚本中添加时间延迟?

How do I put a time delay in a Python script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

憧憬巴黎街头的黎明 2024-07-19 09:34:23

这会延迟 2.5 秒:

import time

time.sleep(2.5)

这是另一个示例,其中大约每分钟运行一次:

import time

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

This delays for 2.5 seconds:

import time

time.sleep(2.5)

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).
世态炎凉 2024-07-19 09:34:23

使用 sleep() 中的 sleep() >时间模块。 它可以采用浮点参数来实现亚秒级分辨率。

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

Use sleep() from the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1)  # Time in seconds
一百个冬季 2024-07-19 09:34:23

如何在Python中实现时间延迟?

在单个线程中,我建议 sleep 函数

>>> from time import sleep

>>> sleep(4)

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

将其用于此目的,或者只是延迟函数的执行。 例如:

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

“万岁!” 在我按 Enter 后 3 秒打印。

在多个线程和进程中使用 sleep 的示例

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

为了进行演示,创建一个像这样的脚本(我首先在交互式 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()

此脚本的示例输出:

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

多线程

您可以使用 Timer threading 对象:

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

>>>

空行说明该函数打印到我的标准输出,我必须按 Enter 以确保我处于提示状态。

这种方法的优点是,当 Timer 线程等待时,我可以做其他事情,在本例中,在函数执行之前按一下 Enter 一次(请参阅第一个空提示)。

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

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 function 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!" is printed 3 seconds after I hit Enter.

Example using sleep with multiple threads and processes

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

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):

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 output, and I had to hit Enter to ensure I was on a prompt.

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).

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 subprocess.

白芷 2024-07-19 09:34:23

还可以使用以下方法来实现延迟。

第一种方法:

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

第二种延迟方法是使用隐式等待方法:

 driver.implicitly_wait(5)

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

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

Delays can be also implemented by using the following methods.

The first method:

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

The second method to delay would be using the implicit wait method:

 driver.implicitly_wait(5)

The 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'))
随心而道 2024-07-19 09:34:23

我知道的有五种方法:time.sleep()pygame.time.wait()、matplotlib的pyplot.pause().after()asyncio.sleep()


time.sleep() 示例(如果使用 tkinter,请勿使用):

import time
print('Hello')
time.sleep(5) # Number of seconds
print('Bye')

pygame.time.wait() 示例(如果您不使用 pygame 窗口,则不推荐,但您可以立即退出窗口):

import pygame
# If you are going to use the time module
# don't do "from pygame import *"
pygame.init()
print('Hello')
pygame.time.wait(5000) # Milliseconds
print('Bye')

matplotlib 的函数 pyplot.pause() 示例(如果您不使用图形,则不推荐,但您可以立即退出图形):

import matplotlib
print('Hello')
matplotlib.pyplot.pause(5) # Seconds
print('Bye')

.after( ) 方法(最好使用 Tkinter):

import tkinter as tk # Tkinter for Python 2
root = tk.Tk()
print('Hello')
def ohhi():
    print('Oh, hi!')
root.after(5000, ohhi) # Milliseconds and then a function
print('Bye')

最后,asyncio.sleep() 方法(必须位于异步循环中):

await asyncio.sleep(5)

There are five methods which I know: time.sleep(), pygame.time.wait(), matplotlib's pyplot.pause(), .after(), and asyncio.sleep().


time.sleep() example (do not use if using tkinter):

import time
print('Hello')
time.sleep(5) # Number of seconds
print('Bye')

pygame.time.wait() example (not recommended if you are not using the pygame window, but you could exit the window instantly):

import pygame
# If you are going to use the time module
# don't do "from pygame import *"
pygame.init()
print('Hello')
pygame.time.wait(5000) # Milliseconds
print('Bye')

matplotlib's function pyplot.pause() example (not recommended if you are not using the graph, but you could exit the graph instantly):

import matplotlib
print('Hello')
matplotlib.pyplot.pause(5) # Seconds
print('Bye')

The .after() method (best with Tkinter):

import tkinter as tk # Tkinter for Python 2
root = tk.Tk()
print('Hello')
def ohhi():
    print('Oh, hi!')
root.after(5000, ohhi) # Milliseconds and then a function
print('Bye')

Finally, the asyncio.sleep() method (has to be in an async loop):

await asyncio.sleep(5)
葵雨 2024-07-19 09:34:23

使用昏昏欲睡的生成器来一点乐趣。

问题是关于时间延迟。 它可以是固定时间,但在某些情况下,我们可能需要自上次以来测量的延迟。 这是一种可能的解决方案:

自上次以来测量的延迟(定期醒来)

这种情况可能是,我们希望尽可能定期地做某事,并且不想打扰所有 last_time、< code>next_time 遍布我们的代码。

蜂鸣器生成器

下面的代码 (sleepy.py) 定义了一个 buzzergen 生成器:

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

调用常规的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()

并运行它,我们看到:

1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47

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

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

并运行我们可能会看到:

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)

正如我们所看到的,这个蜂鸣器并不太严格,即使我们睡过头并且超出了正常的作息时间,它也可以让我们赶上定期的睡眠时间间隔。

A bit of fun with a 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 solution:

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.

Buzzer generator

The following code (sleepy.py) defines a buzzergen generator:

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 with regular sleepy intervals even if we oversleep and get out of regular schedule.

甜是你 2024-07-19 09:34:23

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

如果您使用 Tkinter,不要使用 time.sleep(),因为它会使您的程序变得混乱。 这发生在我身上。 相反,请使用 root.after() 并用毫秒替换任意秒数的值。 例如,time.sleep(1) 相当于 Tkinter 中的 root.after(1000)

否则,time.sleep(),许多答案已经指出,这是要走的路。

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.

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. For example, time.sleep(1) is equivalent to root.after(1000) in Tkinter.

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

长发绾君心 2024-07-19 09:34:23

延迟是通过时间库完成的,特别是time.sleep() 函数。

只是让它等待一秒钟:

from time import sleep
sleep(1)

这是有效的,因为通过这样做:

from time import sleep

您提取 睡眠功能来自时间库,这意味着您可以直接使用:

sleep(seconds)

来调用它,而不必键入

time.sleep()

键入的内容太长了。

使用此方法,您将无法访问时间库 并且不能有一个名为 sleep 的变量。 但您可以创建一个名为 time 的变量。

执行 from [library] import [function] (,如果您只想要模块的某些部分,[function2]) 非常有用。

您同样可以这样做:

import time
time.sleep(1)

并且您可以访问 时间库的其他功能 就像time.clock() 只要您输入 time.[function](),但您无法创建变量 time,因为它会覆盖导入。 解决此问题的方法

import time as t

是允许您引用 时间库 作为t,允许您执行以下操作:

t.sleep()

这适用于任何库。

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

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.

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

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 because it would overwrite the import. A solution to this to do

import time as t

which would allow you to reference the time library as t, allowing you to do:

t.sleep()

This works on any library.

时常饿 2024-07-19 09:34:23

如果您想在 Python 脚本中添加时间延迟:

使用 time.sleepEvent().wait 像这样:

from threading import Event
from time import sleep

delay_in_sec = 2

# Use time.sleep like this
sleep(delay_in_sec)         # Returns None
print(f'slept for {delay_in_sec} seconds')

# Or use Event().wait like this
Event().wait(delay_in_sec)  # Returns False
print(f'waited for {delay_in_sec} seconds')

但是,如果您想延迟函数的执行,请执行以下操作:

使用 threading.Timer 像这样:

from threading import Timer

delay_in_sec = 2

def hello(delay_in_sec):
    print(f'function called after {delay_in_sec} seconds')

t = Timer(delay_in_sec, hello, [delay_in_sec])  # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start()  # Returns None
print("Started")

输出:

Started
function called after 2 seconds

为什么使用后面的方法?

  • 不会停止整个脚本的执行(除了您传递给它的函数)。
  • 启动计时器后,您还可以通过执行 timer_obj.cancel() 来停止它。

If you would like to put a time delay in a Python script:

Use time.sleep or Event().wait like this:

from threading import Event
from time import sleep

delay_in_sec = 2

# Use time.sleep like this
sleep(delay_in_sec)         # Returns None
print(f'slept for {delay_in_sec} seconds')

# Or use Event().wait like this
Event().wait(delay_in_sec)  # Returns False
print(f'waited for {delay_in_sec} seconds')

However, if you want to delay the execution of a function do this:

Use threading.Timer like this:

from threading import Timer

delay_in_sec = 2

def hello(delay_in_sec):
    print(f'function called after {delay_in_sec} seconds')

t = Timer(delay_in_sec, hello, [delay_in_sec])  # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start()  # Returns None
print("Started")

Outputs:

Started
function called after 2 seconds

Why use the later approach?

  • It does not stop execution of the whole script (except for the function you pass it).
  • After starting the timer you can also stop it by doing timer_obj.cancel().
话少情深 2024-07-19 09:34:23

asyncio.sleep

请注意,在最新的 Python 版本(Python 3.4 或更高版本)中,您可以使用 asyncio.sleep。 它与异步编程和asyncio有关。 看看下一个例子:

import asyncio
from datetime import datetime

@asyncio.coroutine
def countdown(iteration_name, countdown_sec):
    """
    Just count for some countdown_sec seconds and do nothing else
    """
    while countdown_sec > 0:
       print(f'{iteration_name} iterates: {countdown_sec} seconds')
       yield from asyncio.sleep(1)
       countdown_sec -= 1

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(countdown('First Count', 2)),
         asyncio.ensure_future(countdown('Second Count', 3))]

start_time = datetime.utcnow()

# Run both methods. How much time will both run...?
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

print(f'total running time: {datetime.utcnow() - start_time}')

我们可能认为第一个方法会“休眠”2秒,第二个方法会“休眠”3秒,这段代码总共运行5秒。 但会打印:

total_running_time: 0:00:03.01286

建议阅读 asyncio 官方文档 了解更多详情。

asyncio.sleep

Notice in recent Python versions (Python 3.4 or higher) you can use asyncio.sleep. It's related to asynchronous programming and asyncio. Check out next example:

import asyncio
from datetime import datetime

@asyncio.coroutine
def countdown(iteration_name, countdown_sec):
    """
    Just count for some countdown_sec seconds and do nothing else
    """
    while countdown_sec > 0:
       print(f'{iteration_name} iterates: {countdown_sec} seconds')
       yield from asyncio.sleep(1)
       countdown_sec -= 1

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(countdown('First Count', 2)),
         asyncio.ensure_future(countdown('Second Count', 3))]

start_time = datetime.utcnow()

# Run both methods. How much time will both run...?
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

print(f'total running time: {datetime.utcnow() - start_time}')

We may think it will "sleep" for 2 seconds for first method and then 3 seconds in the second method, a total of 5 seconds running time of this code. But it will print:

total_running_time: 0:00:03.01286

It is recommended to read asyncio official documentation for more details.

凉城已无爱 2024-07-19 09:34:23

虽然其他人都建议使用事实上的 time 模块,但我想我应该使用 matplotlibpyplot 函数分享一种不同的方法,暂停

示例

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

通常,这用于防止绘图在绘制后立即消失或制作粗糙的动画。

如果您已经导入了 matplotlib,这将为您节省一次导入

While everyone else has suggested the de facto time module, I thought I'd share a different method using matplotlib's pyplot function, 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.

┊风居住的梦幻卍 2024-07-19 09:34:23

这是时间延迟的一个简单示例:

import time

def delay(period='5'):
    # If the user enters nothing, it'll wait 5 seconds
    try:
        # If the user not enters a int, I'll just return ''
        time.sleep(period)
    except:
        return ''

另一个,在 Tkinter 中:

import tkinter

def tick():
    pass

root = Tk()
delay = 100 # Time in milliseconds
root.after(delay, tick)
root.mainloop()

This is an easy example of a time delay:

import time

def delay(period='5'):
    # If the user enters nothing, it'll wait 5 seconds
    try:
        # If the user not enters a int, I'll just return ''
        time.sleep(period)
    except:
        return ''

Another, in Tkinter:

import tkinter

def tick():
    pass

root = Tk()
delay = 100 # Time in milliseconds
root.after(delay, tick)
root.mainloop()
无法言说的痛 2024-07-19 09:34:23

您也可以尝试以下操作:

import time
# The time now
start = time.time() 
while time.time() - start < 10: # Run 1- seconds
    pass
# Do the job

现在 shell 不会崩溃或没有反应。

You also can try this:

import time
# The time now
start = time.time() 
while time.time() - start < 10: # Run 1- seconds
    pass
# Do the job

Now the shell will not crash or not react.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文