简体   繁体   English

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

[英]Efficient ways to pause a Python script and wait for condition?

I have a program that detects when some process is running.我有一个程序可以检测某个进程何时运行。 I currently have a while loop set up to constantly detect when the desired process is running:我目前设置了一个while循环来不断检测所需进程何时运行:

while not process_exists('PROCESS_NAME'):
    pass

when the condition evaluates as True, it moves on.当条件评估为 True 时,它会继续。

Are there any better ways of doing this?有没有更好的方法来做到这一点?

This should do the trick这应该可以解决问题

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

But Kickin_Wing raises a good point that you should include a timeout period to make this more resilient.但是 Kickin_Wing 提出了一个很好的观点,即您应该包括一个超时时间以使其更具弹性。 One way you could do that is like this (adjusting the timeoutCtr check in the if statement to your needs)您可以这样做的一种方法是(根据您的需要调整 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)

This way, your program will stop and let you know what's going on if the process name takes too long to appear instead of simply trying and failing to do what you were planning to do after process_exists() and giving a more confusing runtime error这样,如果进程名称出现时间过长,您的程序将停止并让您知道发生了什么,而不是简单地尝试并且未能执行您计划在 process_exists() 之后执行的操作并给出更令人困惑的运行时错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM