我将如何在此脚本中实现循环?

时间:2019-01-18 12:59:34

标签: python loops

如何循环这段代码,直到它检测到不和谐不再运行并打印出else行?

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 个答案:

答案 0 :(得分:1)

您可以使用具有中断条件的无限循环。因此,在代码末尾,您将得到类似的内容:

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

这将通过连续调用checkIfProcessRunning('discord')而起作用。如果返回True,则它将继续循环并再次检查。返回False时,循环将中断。

但是,这将打印很多Discord is running,因此您可能希望在该循环中使用某种类型的睡眠方法,以仅每5秒或这样的时间检查一次:

from time import sleep

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