How would I go about implementing a loop in this script?

55 views Asked by At

How do I loop this code until it detects discord isn't running anymore and prints out the else line?

import psutil

def checkIfProcessRunning(processName):

for proc in psutil.process_iter():
    try:           
        if processName.lower() in proc.name().lower():
            return True
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        pass
return False;

if checkIfProcessRunning('discord'):
  print('Discord is running')
else:
  print('Discord is NOT running')
1

There are 1 answers

0
TheStrangeQuark On BEST ANSWER

You can use an infinite loop that has a break condition. So at the end of your code you would have something like:

while checkIfProcessRunning('discord'):
    print('Discord is running')
print('Discord is NOT running')

This will work by continually calling checkIfProcessRunning('discord'). If it returns True, then it continues in the loop and checks again. When you returns False, then the loop will break.

However, this will be printing a lot of Discord is running, so you might want to have some type of sleep method in that loop to only check every 5 seconds or some amount of time like this:

from time import sleep

while checkIfProcessRunning('discord'):
    print('Discord is running')
    sleep(5)
print('Discord is NOT running')