Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中设置时间延迟?_Python_Python 3.x_Delay_Sleep_Timedelay - Fatal编程技术网

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

如何在Python中设置时间延迟?,python,python-3.x,delay,sleep,timedelay,Python,Python 3.x,Delay,Sleep,Timedelay,我想知道如何在Python脚本中设置时间延迟。您可以使用。它可以采用浮点参数进行亚秒级分辨率 from time import sleep sleep(0.1) # Time in seconds 下面是另一个示例,其中大约每分钟运行一次: import time while True: print("This prints once a minute.") time.sleep(60) # Delay for 1 minute (60 seconds). 和一个困倦的人在一

我想知道如何在Python脚本中设置时间延迟。

您可以使用。它可以采用浮点参数进行亚秒级分辨率

from time import sleep
sleep(0.1) # Time in seconds
下面是另一个示例,其中大约每分钟运行一次:

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

和一个困倦的人在一起有点乐趣

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

自上次测量的延迟(定期醒来) 情况可能是这样的,我们希望尽可能有规律地做一些事情,我们不想为代码周围的所有
上次
下次
的事情而烦恼

蜂鸣器发生器 以下代码(sleepy.py)定义了
蜂鸣器发生器:

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
调用常规蜂鸣器 运行它,我们可以看到:

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标准库中的库是一个可以导入的交互式工具。基本上,您可以创建按钮、框、弹出窗口以及显示为窗口的东西,并使用代码进行操作

如果您使用Tkinter,不要使用
time.sleep()
,因为它会弄脏您的程序。这件事发生在我身上。相反,请使用
root.after()
,并将值替换为毫秒,保留多少秒。例如,
time.sleep(1)
相当于Tkinter中的
root.after(1000)

否则,
time.sleep()

要让它等待一秒钟:

from time import sleep
sleep(1)
这是因为:

from time import sleep
您仅从中提取,这意味着您可以通过以下方式调用它:

sleep(seconds)
而不是打字

time.sleep()
打字的时间太长了

使用此方法,您将无法访问的其他功能,也无法拥有名为
sleep
的变量。但是您可以创建一个名为
time
的变量

如果您只需要模块的某些部分,那么这样做是很好的

你也可以这样做:

import time
time.sleep(1)
只要键入
time.[function]()
,您就可以访问类似的其他功能,但无法创建变量time,因为它会覆盖导入。解决这个问题的办法是什么

import time as t
这将允许您引用as
t
,允许您执行以下操作:

t.sleep()
这适用于任何图书馆

如何在Python中设置时间延迟? 在单个线程中,我建议:

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

为此目的使用它,或者只是为了延迟函数的执行。例如:

>>> def party_time():
...     print('hooray!')
...
>>> sleep(3); party_time()
hooray!
“万岁!”在我按Enter键3秒后打印出来

使用多线程和进程的
睡眠
示例
同样,
sleep
挂起您的线程-它使用几乎为零的处理能力

为了演示,创建这样一个脚本(我首先在交互式Python 3.5 shell中尝试了这一点,但由于某些原因,子进程后来找不到
party\u
函数):

此脚本的输出示例:

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
对象触发稍后在单独线程中调用的函数:

空行说明函数打印到了我的标准输出,我必须按Enter键以确保出现提示

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


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

延迟也可以通过使用以下方法来实现

第一种方法:

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
模块,但我认为我应该使用
matplotlib
pyplot
函数来共享一种不同的方法

一个例子 通常,这用于防止打印后打印立即消失或制作粗糙的动画


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

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


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


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


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


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


最后是
asyncio.sleep()
方法:

import asyncio
asyncio.sleep(5)

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

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 ''
另一项是:

异步睡眠 注意,在最近的Python版本(Python3.4或更高版本)中,您可以使用
asyncio.sleep
。它与异步编程和异步IO有关。查看下一个示例:

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秒
 driver.implicitly_wait(5)
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))
from matplotlib import pyplot as plt
plt.pause(5)    # Pauses the program for 5 seconds
import time
print('Hello')
time.sleep(5) # Number of seconds
print('Bye')
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')
import matplotlib
print('Hello')
matplotlib.pyplot.pause(5) # Seconds
print('Bye')
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')
import asyncio
asyncio.sleep(5)
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 ''
import tkinter

def tick():
    pass

root = Tk()
delay = 100 # Time in milliseconds
root.after(delay, tick)
root.mainloop()
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}')
total_running_time: 0:00:03.01286
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')
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
import time
# The time now
start = time.time() 
while time.time() - start < 10: # Run 1- seconds
    pass
# Do the job