'Check if a program has stopped working in Windows using python

I am trying to create a python program that can detect if a particular program I use stops working so it can then notify me that it has stopped working.

Currently, I have this:

def isresponding(name):
    os.system('tasklist /FI "IMAGENAME eq %s" /FI "STATUS eq not responding" > tmp.txt' % name)
    tmp = open('tmp.txt', 'r')
    a = tmp.readlines()
    print(a)
    tmp.close()
    if a[-1].split()[0] == name:
        print("True")
        return True
    else:
        print("False")
        return False

The problem with this code is this it checks if the program is not responding however, my program gives this instead but doesn't say not responding

Image showing error

Is there any way python that can detect if this happens or do I need to use something else?

Any help would be appreciated.



Solution 1:[1]

Try psutil or subprocess. If you want to dive into Windows, I recommend pywin32

from psutil import process_iter

for element in process_iter():
    print(element)

Output:

sutil.Process(pid=0, name='System Idle Process', status='running')
psutil.Process(pid=4, name='System', status='running')
psutil.Process(pid=100, name='Registry', status='running', started='2022-04-20 00:27:07')
psutil.Process(pid=316, name='fontdrvhost.exe', status='running', started='2022-04-20 00:27:16')
psutil.Process(pid=436, name='smss.exe', status='running', started='2022-04-20 00:27:09')
psutil.Process(pid=560, name='dllhost.exe', status='running', started='2022-04-22 12:05:10')
psutil.Process(pid=688, name='svchost.exe', status='running', started='2022-04-20 00:27:18')
psutil.Process(pid=700, name='csrss.exe', status='running', started='2022-04-20 00:27:15')
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vovin