1

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 not process_exists('PROCESS_NAME'):
    pass

when the condition evaluates as True, it moves on.

Are there any better ways of doing this?

Scene
  • 489
  • 4
  • 16
  • 2
    What if the process never exists? Can you include a timeout period that will exit the program or raise an error? – Lateralus May 14 '20 at 16:01
  • Have a look at [How do I get my Python program to sleep for 50 milliseconds?](https://stackoverflow.com/questions/377454/how-do-i-get-my-python-program-to-sleep-for-50-milliseconds). The `time` module will also allow you to implement a timeout. – mattst May 14 '20 at 16:08

1 Answers1

0

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. One way you could do that is like this (adjusting the timeoutCtr check in the if statement to your needs)

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