我想知道如何在Python脚本中加时间延迟。
我想知道如何在Python脚本中加时间延迟。
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
这是另一个例子,大约每分钟运行一次:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
这是另一个例子,大约每分钟运行一次:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
你可以使用 sleep()
功能在时间模块中。它可以采用浮动参数进行亚秒级分辨率。
from time import sleep
sleep(0.1) # Time in seconds.
请阅读 https://web.archive.org/web/20090207081238/http://faqts.com/knowledge_base/view.phtml/aid/2609/fid/378,这可以帮助你进一步:
在时间模块中尝试睡眠功能。
import time time.sleep(60)
把它放在一个
while
循环和语句只会执行 分钟...这允许您以预定义的间隔运行语句 无论命令花了多长时间(只要它花费的时间少于 一分钟或5或60或其他任何你设置它)例如,我想 每分钟运行一次ping。如果我只是time.sleep(60)
要么time.sleep(45)
甚至,ping也不会总是花费相同的时间。这是 代码:)time.sleep(time.localtime(time.time())[5])
该
[5]
只是把秒数拉出来time.localtime()
回归 值。伟大的事情
time.sleep
是它支持浮点 数字!import time time.sleep(0.1)
你可以通过简单地做到这一点:
from time import sleep
# Doing stuff
sleep(0.5) # Sleeping half a second (sleep() uses seconds, but you can also use floats)
# Doing stuff...
困了一点有趣 发电机。
问题是时间延迟。它可以是固定的时间,但在某些情况下,我们可能需要从上次开始测量延迟。这是一个可能的解决方案:
情况可能是,我们希望尽可能经常地做一些事情,我们不想打扰所有人 last_time
, 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
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)
正如我们所看到的,这种蜂鸣器不会过于僵硬,即使我们睡过头而且不按规定时间安排,也能让我们赶上常规的困倦时间间隔。
如何在Python中延迟时间?
在一个线程中我建议睡眠功能:
>>> from time import sleep
>>> sleep(4)
这实际上暂停了操作系统调用它的线程的处理,允许其他线程和进程在休眠时执行。
将其用于此目的,或仅仅是为了延迟执行某个功能。例如:
>>> def party_time():
... print('hooray!')
...
>>> sleep(3); party_time()
hooray!
“万岁!”我打了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
线程对象:
>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!
>>>
空白行说明该功能打印到我的标准输出,我不得不打 输入 确保我提示。
这种方法的好处是,而 Timer
线程在等待,我能够做其他事情,在这种情况下,击中 输入 一次 - 在执行函数之前(参见第一个空提示)。
多处理库中没有相应的对象。你可以创建一个,但它可能不存在是有原因的。对于简单的计时器而言,子线程比整个新的子进程更有意义。
Python标准库中的tkinter库是一个可以导入的交互式工具。基本上,您可以创建按钮和框,弹出窗口以及显示为您使用代码操作的窗口的内容。
如果您使用tkinter,请勿使用 TIME.SLEEP()
因为它会破坏你的程序。这发生在我身上。相反,使用 root.after()
并用毫秒替换多秒的值。例如, time.sleep(1)
相当于 root.after(1000)
在tkinter。
除此以外, time.sleep()
许多答案指出,这是要走的路。
可以使用三种方法实现延迟。
让我们从最简单的一个开始:
import time
time.sleep(5) # Delay for 5 seconds.
第二种延迟方法是使用隐式等待方法:
driver.implicitly_wait(5)
当您必须等到特定操作完成或找到元素时,第三种方法更有用:
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))
要延迟时间,你应该导入 time
模块。使用该模块,您只需要写:
time.sleep(The amount of time)
例如,如果要在计算机运行另一行之前设置一秒的时间延迟,则应该放置:
time.sleep(1)
print('Hello, World!')
就这样 :)
我知道有4种方法: time.sleep()
, pygame.time.wait()
,matplotlib的 pyplot.pause()
,和 .after()
。
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')
延迟是通过 时间库,特别是 time.sleep() 功能...
要让它等待一秒钟:
from time import sleep
sleep(1)
这有效,因为通过这样做:
from time import sleep
你解压缩了 睡眠功能 只要 来自 时间库 这意味着您可以通过以下方式调用它:
sleep(seconds)
而不是输入
time.sleep()
打字很长很难。
使用此方法,您将无法访问其他功能 时间库 你不能有一个名为sleep的变量。但是你可以创建一个名为time的变量。
干 来自[library] import [function](,[function2]) 如果您只是想要模块的某些部分,那就太棒了。
你可以同样这样做
import time
time.sleep(1)
你可以访问其他功能 时间库喜欢 time.clock()
只要你输入 时间。功能,但你无法创建变量时间。