Python - 寻找在无限循环中暂时停止函数调用的方法

0 投票
2 回答
1093 浏览
提问于 2025-04-16 16:52

我有一个循环作为我的主函数。在这个循环里,我会检查几个条件,如果满足条件就调用相应的函数。有一个特定的函数,我不想在过去的两分钟内再次调用它。如果我在这个函数里加一个等待(WAIT())的语句,那就会导致其他条件的检查在这段时间内无法进行。

在我尝试让myFunction()暂停之前,代码大概是这样的:

while not(exit condition):
    if(test):
        otherFunction()
    if(test):
        otherFunction()
    if(test):
        myFunction()

我希望myFunction()每两分钟最多只运行一次。我可以在里面加一个wait(120),但那样会导致其他的函数在这段时间内无法被调用。

我尝试过:

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),我似乎无法追踪代码的执行过程,看看它是怎么运行的。

2 个回答

0

你总是把“现在”设置为当前的时间。在else分支中,你总是把“那时”也设置为现在。所以“差值”总是代表了上一次和这一次执行if条件之间经过的时间。而“设置”的值在你的代码中只会改变一次,之后不会再被重置为“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
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()

撰写回答