暂停Python脚本并等待条件的有效方法?

问题描述 投票:0回答:1

我有一个程序可以检测某些进程在何时运行。我目前设置了一个while循环来不断检测所需进程的运行时间:

while not process_exists('PROCESS_NAME'):
    pass

当条件评估为True时,它将继续。

还有其他更好的方法吗?

python performance while-loop process detection
1个回答
0
投票

这应该可以解决问题

from time import sleep
. . .
while not process_exists('PROCESS_NAME'):
    sleep(0.05)

但是Kickin_Wing提出了一个很好的观点,您应该包括一个超时时间,以使其更具弹性。您可以这样做的一种方法是这样的(根据需要调整if语句中的timeoutCtr检查)

from time import sleep
. . .
timeoutCtr = 0
while not process_exists('PROCESS_NAME'):
    timeoutCtr = timeoutCtr + 1
    if timeoutCtr > 100:
        print("error: PROCESS_NAME did not appear within 5 seconds")
        exit(1)
    sleep(0.05)

这样,您的程序将停止运行,并让您知道发生了什么事情,如果进程名称花费的时间太长而不是简单地尝试并失败并在process_exists()之后执行您打算做的事情,并给出更令人困惑的运行时错误

© www.soinside.com 2019 - 2024. All rights reserved.