如何延迟时间?
如何在 Python 脚本中添加时间延迟?
How do I put a time delay in a Python script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何在 Python 脚本中添加时间延迟?
How do I put a time delay in a Python script?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(13)
这会延迟 2.5 秒:
这是另一个示例,其中大约每分钟运行一次:
This delays for 2.5 seconds:
Here is another example where something is run approximately once a minute:
使用
sleep()
中的sleep()
>时间模块。 它可以采用浮点参数来实现亚秒级分辨率。Use
sleep()
from thetime
module. It can take a float argument for sub-second resolution.在单个线程中,我建议 sleep 函数:
这个函数实际上挂起操作系统调用它的线程的处理,允许其他线程和进程在其休眠时执行。
将其用于此目的,或者只是延迟函数的执行。 例如:
“万岁!” 在我按 Enter 后 3 秒打印。
在多个线程和进程中使用
sleep
的示例同样,
sleep
会挂起您的线程 - 它使用的处理能力几乎为零。为了进行演示,创建一个像这样的脚本(我首先在交互式 Python 3.5 shell 中尝试此操作,但由于某种原因子进程无法找到
party_later
函数):此脚本的示例输出:
多线程
您可以使用
Timer
threading 对象:空行说明该函数打印到我的标准输出,我必须按 Enter 以确保我处于提示状态。
这种方法的优点是,当 Timer 线程等待时,我可以做其他事情,在本例中,在函数执行之前按一下 Enter 一次(请参阅第一个空提示)。
多处理库中没有相应的对象。 您可以创建一个,但它可能由于某种原因不存在。 对于简单的计时器来说,子线程比全新的子进程更有意义。
In a single thread I suggest the sleep function:
This function actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps.
Use it for that purpose, or simply to delay a function from executing. For example:
"hooray!" is printed 3 seconds after I hit Enter.
Example using
sleep
with multiple threads and processesAgain,
sleep
suspends your thread - it uses next to zero processing power.To demonstrate, create a script like this (I first attempted this in an interactive Python 3.5 shell, but sub-processes can't find the
party_later
function for some reason):Example output from this script:
Multithreading
You can trigger a function to be called at a later time in a separate thread with the
Timer
threading object:The blank line illustrates that the function printed to my standard output, and I had to hit Enter to ensure I was on a prompt.
The upside of this method is that while the
Timer
thread was waiting, I was able to do other things, in this case, hitting Enter one time - before the function executed (see the first empty prompt).There isn't a respective object in the multiprocessing library. You can create one, but it probably doesn't exist for a reason. A sub-thread makes a lot more sense for a simple timer than a whole new subprocess.
还可以使用以下方法来实现延迟。
第一种方法:
第二种延迟方法是使用隐式等待方法:
当您必须等待特定操作完成或找到元素时,第三种方法更有用:
Delays can be also implemented by using the following methods.
The first method:
The second method to delay would be using the implicit wait method:
The third method is more useful when you have to wait until a particular action is completed or until an element is found:
我知道的有五种方法:
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() 方法(必须位于异步循环中):
There are five methods which I know:
time.sleep()
,pygame.time.wait()
, matplotlib'spyplot.pause()
,.after()
, andasyncio.sleep()
.time.sleep()
example (do not use if using tkinter):pygame.time.wait()
example (not recommended if you are not using the pygame window, but you could exit the window instantly):matplotlib's function
pyplot.pause()
example (not recommended if you are not using the graph, but you could exit the graph instantly):The
.after()
method (best with Tkinter):Finally, the
asyncio.sleep()
method (has to be in an async loop):使用昏昏欲睡的生成器来一点乐趣。
问题是关于时间延迟。 它可以是固定时间,但在某些情况下,我们可能需要自上次以来测量的延迟。 这是一种可能的解决方案:
自上次以来测量的延迟(定期醒来)
这种情况可能是,我们希望尽可能定期地做某事,并且不想打扰所有
last_time
、< code>next_time 遍布我们的代码。蜂鸣器生成器
下面的代码 (sleepy.py) 定义了一个
buzzergen
生成器:调用常规的buzzergen
并运行它,我们看到:
我们也可以直接在循环中使用它:
并运行我们可能会看到:
正如我们所看到的,这个蜂鸣器并不太严格,即使我们睡过头并且超出了正常的作息时间,它也可以让我们赶上定期的睡眠时间间隔。
A bit of fun with a sleepy generator.
The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solution:
Delay measured since last time (waking up regularly)
The situation can be, we want to do something as regularly as possible and we do not want to bother with all the
last_time
,next_time
stuff all around our code.Buzzer generator
The following code (sleepy.py) defines a
buzzergen
generator:Invoking regular buzzergen
And running it we see:
We can also use it directly in a loop:
And running it we might see:
As we see, this buzzer is not too rigid and allow us to catch up with regular sleepy intervals even if we oversleep and get out of regular schedule.
Python 标准库中的 Tkinter 库是一个可以导入的交互式工具。 基本上,您可以创建按钮、框、弹出窗口以及显示为窗口的内容,您可以使用代码进行操作。
如果您使用 Tkinter,不要使用
time.sleep()
,因为它会使您的程序变得混乱。 这发生在我身上。 相反,请使用 root.after() 并用毫秒替换任意秒数的值。 例如,time.sleep(1)
相当于 Tkinter 中的root.after(1000)
。否则,
time.sleep()
,许多答案已经指出,这是要走的路。The Tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.
If you use Tkinter, do not use
time.sleep()
, because it will muck up your program. This happened to me. Instead, useroot.after()
and replace the values for however many seconds, with a milliseconds. For example,time.sleep(1)
is equivalent toroot.after(1000)
in Tkinter.Otherwise,
time.sleep()
, which many answers have pointed out, which is the way to go.延迟是通过时间库完成的,特别是
time.sleep()
函数。只是让它等待一秒钟:
这是有效的,因为通过这样做:
您提取 睡眠功能仅来自时间库,这意味着您可以直接使用:
来调用它,而不必键入
键入的内容太长了。
使用此方法,您将无法访问时间库 并且不能有一个名为
sleep
的变量。 但您可以创建一个名为time
的变量。执行
from [library] import [function] (,如果您只想要模块的某些部分,[function2])
非常有用。您同样可以这样做:
并且您可以访问 时间库的其他功能 就像
time.clock()
只要您输入time.[function]()
,但您无法创建变量 time,因为它会覆盖导入。 解决此问题的方法是允许您引用 时间库 作为
t
,允许您执行以下操作:这适用于任何库。
Delays are done with the time library, specifically the
time.sleep()
function.To just make it wait for a second:
This works because by doing:
You extract the sleep function only from the time library, which means you can just call it with:
Rather than having to type out
Which is awkwardly long to type.
With this method, you wouldn't get access to the other features of the time library and you can't have a variable called
sleep
. But you could create a variable calledtime
.Doing
from [library] import [function] (, [function2])
is great if you just want certain parts of a module.You could equally do it as:
and you would have access to the other features of the time library like
time.clock()
as long as you typetime.[function]()
, but you couldn't create the variable time because it would overwrite the import. A solution to this to dowhich would allow you to reference the time library as
t
, allowing you to do:This works on any library.
如果您想在 Python 脚本中添加时间延迟:
使用
time.sleep
或Event().wait
像这样:但是,如果您想延迟函数的执行,请执行以下操作:
使用
threading.Timer
像这样:输出:
为什么使用后面的方法?
timer_obj.cancel()
来停止它。If you would like to put a time delay in a Python script:
Use
time.sleep
orEvent().wait
like this:However, if you want to delay the execution of a function do this:
Use
threading.Timer
like this:Outputs:
Why use the later approach?
timer_obj.cancel()
.asyncio.sleep
请注意,在最新的 Python 版本(Python 3.4 或更高版本)中,您可以使用
asyncio.sleep
。 它与异步编程和asyncio有关。 看看下一个例子:我们可能认为第一个方法会“休眠”2秒,第二个方法会“休眠”3秒,这段代码总共运行5秒。 但会打印:
建议阅读 asyncio 官方文档 了解更多详情。
asyncio.sleep
Notice in recent Python versions (Python 3.4 or higher) you can use
asyncio.sleep
. It's related to asynchronous programming and asyncio. Check out next example:We may think it will "sleep" for 2 seconds for first method and then 3 seconds in the second method, a total of 5 seconds running time of this code. But it will print:
It is recommended to read asyncio official documentation for more details.
虽然其他人都建议使用事实上的
time
模块,但我想我应该使用matplotlib
的pyplot
函数分享一种不同的方法,暂停
。示例
通常,这用于防止绘图在绘制后立即消失或制作粗糙的动画。
如果您已经导入了
matplotlib
,这将为您节省一次导入
。While everyone else has suggested the de facto
time
module, I thought I'd share a different method usingmatplotlib
'spyplot
function,pause
.An example
Typically this is used to prevent the plot from disappearing as soon as it is plotted or to make crude animations.
This would save you an
import
if you already havematplotlib
imported.这是时间延迟的一个简单示例:
另一个,在 Tkinter 中:
This is an easy example of a time delay:
Another, in Tkinter:
您也可以尝试以下操作:
现在 shell 不会崩溃或没有反应。
You also can try this:
Now the shell will not crash or not react.