Python - 寻找一种方法来停止在无限 while 循环中临时调用函数
我有一个 while 循环作为我的主要功能。在其中我检查了几个 IF 语句并相应地调用函数。如果某个特定函数在过去两分钟内已经运行过,我不想调用它。我不想在函数中放置 WAIT() 语句,因为我希望在此时执行其他 IF 测试。
在尝试暂停 myFunction() 之前,代码是这样的,
while not(exit condition):
if(test):
otherFunction()
if(test):
otherFunction()
if(test):
myFunction()
我希望 myFunction() 最多每两分钟运行一次。我可以在其中放置一个 wait(120) ,但这会阻止当时调用 otherFunction() 。
我尝试过
import time
set = 0
while not(exit condition):
if(test):
otherFunction()
if(test):
otherFunction()
if(test):
now = time.clock()
diff = 0
if not(set):
then = 0
set = 1
else:
diff = now - then
if (diff > 120):
myFunction()
then = now
但没有成功。不确定这是否是正确的方法,如果是,这段代码是否正确。我第一次使用 Python(实际上是 Sikuli)工作,我似乎无法跟踪执行情况以了解它是如何执行的。
i have a while loop as my main function. within it i check several IF statements and call functions accordingly. one particular function i dont want to call if it has been run already within the last two minutes. i dont want to put a WAIT() statement in the function because i want the other IF tests to be performed duiring that time.
the code is something like this before any attempt at pausing myFunction()
while not(exit condition):
if(test):
otherFunction()
if(test):
otherFunction()
if(test):
myFunction()
i want myFunction() to only run at most once every two minutes. i could put a wait(120) within it but that would prevent otherFunction() being called in that time.
i tried
import time
set = 0
while not(exit condition):
if(test):
otherFunction()
if(test):
otherFunction()
if(test):
now = time.clock()
diff = 0
if not(set):
then = 0
set = 1
else:
diff = now - then
if (diff > 120):
myFunction()
then = now
without success. not sure if it is the right approach, and if it is, if this code is correct. my first time working in Python (actually Sikuli) and i dont seem to be able to trace execution through to see how that is being executed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您始终将“现在”设置为当前时间。在 else 分支中,您始终将“then”设置为现在。因此 diff 始终是 if 子句的最后两次执行之间经过的时间。 “set”的值仅在代码中更改,并且永远不会设置回“0”。
你可以这样做(警告:未经测试的代码):
You always set "now" to the current time. In the else branch you always set "then" to now. So diff is then always the time that passed between the last two executions of the if clause. The value of "set" is only changed on in your code and never set back to "0".
You could do something like this instead (warning: untested code):
我认为您基本上走在正确的轨道上,但我的实现方式如下:
编辑
这是一个稍微优化的版本:
I think you're basically on the right track, but here's how I'd implement it:
Edit
Here's a slightly optimized version: