Search code examples
pythonwindowsserviceprocesslong-running-processes

How to check in Python if Windows process is running when its service has stopped?


Some Windows processes keep running for a few minutes after their service has stopped. Is there a way in Python to detect that?


Solution

  • import os
    
    def getTasks(name):
    r = os.popen('tasklist /v').read().strip().split('\n')
    print ('# of tasks is %s' % (len(r)))
    for i in range(len(r)):
        s = r[i]
        if name in r[i]:
            print ('%s in r[i]' %(name))
            return r[i]
    return []
    
    if __name__ == '__main__':
    '''
    This code checks tasklist, and will print the status of a code
    '''
    
         imgName = 'dwm.exe'
    
         notResponding = 'Not Responding'
    
         r = getTasks(imgName)
    
    if not r:
        print('%s - No such process' % (imgName)) 
    
    elif 'Not Responding' in r:
        print('%s is Not responding' % (imgName))
    
    else:
        print('%s is Running or Unknown' % (imgName))
    

    Source

    Important note!!! As the author of the tutorial stated the platform he used was Windows Server 2012 but this code most likely work with other Windows products. At the very least it should give you and idea on how to do what you want.

    Hope its helps!