0

我有一个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),我似乎无法通过跟踪执行来查看它是如何执行的。

4

2 回答 2

2

我认为你基本上是在正确的轨道上,但这是我将如何实现它:

import time

MIN_TIME_DELTA = 120

last_call = time.clock() - (MIN_TIME_DELTA+1)  # init to longer than delta ago
while not exit_condition:
    if test:
        otherFunction()
    if test:
        anotherFunction()
    if test and ((time.clock()-last_call) > MIN_TIME_DELTA):
        last_call = time.clock()
        myFunction()

编辑

这是一个稍微优化的版本:

next_call = time.clock() - 1  # init to a little before now
while not exit_condition:
    if test:
        otherFunction()
    if test:
        anotherFunction()
    if test and (time.clock() > next_call):
        next_call = time.clock() + MIN_TIME_DELTA
        myFunction()
于 2011-05-03T09:53:13.663 回答
0

您总是将“现在”设置为当前时间。在 else 分支中,您总是将“then”设置为现在。因此 diff 始终是 if 子句的最后两次执行之间经过的时间。“set”的值仅在您的代码中更改,永远不会设置回“0”。

你可以这样做(警告:未经测试的代码):

import time

set = 0
last_call_time = time.clock()

while not(exit condition):
    if(test):
        otherFunction()
    if(test):
        otherFunction()
    if(test):
        now = time.clock()
        diff = now - last_call_time
        if (diff > 120)
            myFunction()
            last_call_time = now
于 2011-05-03T08:35:43.790 回答