我怎样才能在Python中延迟时间?

我想知道如何在Python脚本中放一段时间。

import time time.sleep(5) # delays for 5 seconds. You can Also Use 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 ,这可以帮助您进一步:

尝试在时间模块中的睡眠function。

 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) 

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

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

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

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

情况可能是,我们希望尽可能经常做一些事情,而且我们不想在所有代码周围都用last_timenext_time

蜂鸣器发生器

以下代码( sleepy.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 

调用常规蜂鸣器

 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中延迟时间?

在单线程中,我build议睡眠function:

 >>> from time import sleep >>> sleep(4) 

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

为此目的使用它,或者简单地延迟执行的function。 例如:

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

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

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

再次, sleep暂停你的线程 – 它使用接近零的处理能力。

为了演示,创build一个像这样的脚本(我首先在交互式的Python 3.5 shell中尝试了这个,但是由于某些原因,subprocess找不到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 

multithreading

您可以触发一个函数,稍后在具有Timer线程对象的单独线程中调用该函数:

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

空白行说明了打印到我的标准的function,我不得不按Enter键,以确保我在一个提示。

这个方法的好处是,当Timer线程正在等待的时候,我可以做其他事情,在这种情况下,在执行函数之前敲击Enter (见第一个空提示符)。

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

Python标准库中的tkinter库是一个可导入的交互式工具。 基本上,你可以创buildbutton,框和popup窗口,以及用代码操作的窗口。

如果你使用tkinter,不要使用TIME.SLEEP(),因为它会把你的程序弄糟。 这发生在我身上。 相反,请使用root.after(),然后用毫秒代替数秒的值。 例如,time.sleep(1)等同于tkinter上的root.after(1000)。

否则,很多答案指出的time.sleep()就是要走的路。

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

为了让它等待一秒钟:

 from time import sleep sleep(1) 

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

 from time import sleep 

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

 sleep(seconds) 

而不必input:

 time.sleep() 

这是很难打字的。

使用这种方法,您将无法访问时间库的其他function,并且不能使用名为sleep的variables。 但是你可以创build一个叫做time的variables。

如果你只想要一个模块的某些部分,那么从[library] import [function](,[function2])做得很好。

你也可以这样做:

 import time time.sleep(1) 

而且只要input时间,就可以访问time.clock()等时间库的其他function 函数,但不能创build可变时间。

要延迟时间,您应该导入time模块。 而用这个模块你只需要写:

 time.sleep(The amount of time) 

例如,如果您想在计算机运行另一行之前放置一秒的时间延迟,则应该放置:

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

就这样 :)

使用pygame

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