如何在Python脚本中设置时间延迟?


当前回答

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

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

其他回答

使用时间模块中的sleep()。对于亚秒分辨率,它可以使用浮点参数。

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

异步休眠

请注意,在最近的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官方文档以了解更多详细信息。

您也可以尝试以下操作:

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

现在,炮弹不会坠毁,也不会反应。

这将延迟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).

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

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