How can I make a time delay in Python?
我想知道如何在Python脚本中添加时间延迟。
1 2 | import time time.sleep(5) # Delays for 5 seconds. You can also use a float value. |
下面是另一个例子,有些东西大约每分钟运行一次:
1 2 3 4 | import time while True: print("This prints once a minute.") time.sleep(60) # Delay for 1 minute (60 seconds). |
您可以在time模块中使用
1 2 | from time import sleep sleep(0.1) # Time in seconds. |
点击这里了解更多内容。
请阅读这篇文章,它可以帮助你进一步:
Try the sleep function in the time module.
1
2 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 justtime.sleep(60) ortime.sleep(45)
even, the ping will not always take the same amount of time. Here's the
code :)
1 time.sleep(time.localtime(time.time())[5])The
[5] just pulls the seconds out of thetime.localtime() 's return
value.The great thing about
time.sleep is that it supports floating point numbers!
1
2 import time
time.sleep(0.1)More information
How can I make a time delay in Python?
在一个线程中,我建议睡眠功能:
1 2 3 | >>> from time import sleep >>> sleep(4) |
这个函数实际上挂起操作系统调用它的线程的处理,允许其他线程和进程在它休眠时执行。
为此目的使用它,或者只是延迟函数的执行。例如:
1 2 3 4 5 | >>> def party_time(): ... print('hooray!') ... >>> sleep(3); party_time() hooray! |
"万岁!"在我点击Enter 3秒后打印。
例子使用同样,
为了演示,创建一个这样的脚本(我第一次尝试在交互式Python 3.5 shell中这样做,但是由于某种原因,子进程找不到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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() |
这个脚本的示例输出:
1 2 3 4 5 | 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 |
多线程
你可以用
1 2 3 4 5 6 7 | >>> from threading import Timer >>> t = Timer(3, party_time, args=None, kwargs=None) >>> t.start() >>> >>> hooray! >>> |
空白行说明了打印到我的标准输出的函数,我必须按Enter以确保我处于提示符状态。
这个方法的好处是,当
在多处理库中没有相应的对象。你可以创建一个,但它可能并不存在。对于一个简单的定时器来说,子线程比一个全新的子进程更有意义。
用一个昏昏欲睡的发电机做点有趣的事。
这个问题是关于时间延迟的。它可以是固定的时间,但在某些情况下,我们可能需要自上次以来测量的延迟。这里有一个可能的解决方案:
延迟测量自上次(定期醒来)情况可能是,我们希望尽可能定期地做一些事情,而不希望在代码中到处都是
蜂鸣器发生器
下面的代码(sleep .py)定义了一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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() |
运行它,我们看到:
1 2 3 4 5 | 1400102636.46 1400102639.46 1400102642.46 1400102647.47 1400102650.47 |
我们也可以直接在循环中使用它:
1 2 3 4 5 | import random for ring in buzzergen(3): print"now", time.time() print"ring", ring time.sleep(random.choice([0, 2, 4, 6])) |
运行它,我们可能会看到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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) |
正如我们所看到的,这个蜂鸣器并不是太死板,即使我们睡过头或者超出了正常的作息时间,它也能让我们赶上规律的睡眠时间间隔。
我知道的方法有5种:
1 2 3 4 | import time print('Hello') time.sleep(5) #number of seconds print('Bye') |
1 2 3 4 5 6 7 | 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函数
1 2 3 4 | import matplotlib print('Hello') matplotlib.pyplot.pause(5)#seconds print('Bye') |
1 2 3 4 5 6 7 | 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') |
最后,
1 | driver.implicitly_wait(5)#waits 5 seconds |
Python标准库中的tkinter库是一个可以导入的交互式工具。基本上,你可以创建按钮,方框,弹出窗口以及一些你可以用代码操作的窗口。
如果您使用tkinter,不要使用
否则,
延迟是使用时间库完成的,特别是
等一下:
1 2 | from time import sleep sleep(1) |
这是因为:
1 | from time import sleep |
你只从时间库中提取睡眠函数,这意味着你可以用:
1 | sleep(seconds) |
而不是打字
1 | time.sleep() |
打字太长了。
使用此方法,您将无法访问时间库的其他特性,并且不能有一个名为
如果您只想要模块的某些部分,那么执行
你可以这样做:
1 2 | import time time.sleep(1) |
只要输入
1 | import time as t |
这将允许您将时间库引用为
1 | t.sleep() |
这适用于任何库。
在Python中延迟时间的最佳方法是使用
1 2 | import time time.sleep(10) |
用你想要延迟的秒数来代替10。您可以使用"10.1"、"5.07"等格式。
不建议与Tkinter一起使用
延迟可以通过三种方法实现。
让我们从最简单的开始:
1 2 | import time time.sleep(5) # Delay for 5 seconds. |
第二种延迟方法是使用隐式等待方法:
1 | driver.implicitly_wait(5) |
第三种方法更有用,当你必须等到一个特定的动作完成或找到一个元素:
1 | self.wait.until(EC.presence_of_element_located((By.ID, 'UserName')) |
1 2 | import time time.sleep(1) #sleep for one second. |
简单的例子:
1 2 3 4 | #After five seconds,output"hello python!!!" import time time.sleep(5) print("hello python!!!") |
asyncio.sleep
注意,在最近的python版本(python 3.4或更高版本)中,您可以使用asyncio.sleep。它与异步编程和异步通信有关。看看下面的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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秒。但. .它将打印:
1 | total_running_time: 0:00:03.01286 |
建议阅读asyncio官方文档了解更多细节
这是一个时间延迟的简单例子:
1 2 3 4 5 6 7 8 9 | 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:
1 2 3 4 5 6 7 8 9 | import tkinter def tick(): pass root=Tk() delay=100 # time in milliseconds root.after(delay,tick) root.mainloop() |
可以在time包中使用sleep方法来延迟python程序的执行
1 2 | import time time.sleep(1) # Delays for 1 seconds. |
我一直在寻找以前的答案,我只是想建立在他们的基础上。
我经常想要创建一个类型效果,这里是你可以做到这一点(Python 3):
1 2 3 4 5 6 | import time # For pausing def typewrite(text): for i in text: print(i, end="", flush=True) # flush is True, so the result will get printed before waiting time.sleep(0.1) |
在python2中:
1 2 3 4 5 6 7 | import time, sys # Time is for pausing, sys for printing without a new line def typewrite(text): sys.stdout.flush() # flush is True, so the result will get printed before waiting for i in text: sys.stdout.write(i) time.sleep(0.1) |
我希望这对你有所帮助。
如果你想在Python脚本中添加一个时间延迟:
像这样使用
1 2 3 4 5 6 7 8 9 10 11 12 | 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') |
然而,如果你想延迟一个函数的执行,这样做:
像这样使用
1 2 3 4 5 6 7 8 9 10 | 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 sec later with [delay_in_sec] as *args parameter t.start() # returns None print("Started") |
输出:
1 2 | Started function called after 2 seconds |
为什么使用后一种方法?不会停止整个脚本的执行。(除了传递它的函数)启动计时器之后,还可以通过执行
虽然其他人都建议使用事实上的
一个例子
1 2 | from matplotlib import pyplot as plt plt.pause(5) # Pauses the program for 5 seconds |
通常情况下,这是用来防止情节一绘制就消失,或者制作粗糙的动画。
如果已经导入了