Python Psutil - check PID execution

Asked

Viewed 327 times

1

Good Morning!

I am mounting a script in Python to monitor a certain windows task by PID, for this I am using the Python Psutil library.

The problem is that whenever I run the code it brings the status of the task as running, even when it’s tasks is locked in windows (Not responding).

Does anyone know if there’s another way to know if the task is stopped?

import psutil
import time
import smtplib
from Include import TC_Email
from email.mime.text import MIMEText
from datetime import datetime

time.sleep(15)
print(datetime.now().strftime('%d/%m/%Y %H:%M:%S'))
validacao_processo = False

for proc in psutil.process_iter(attrs=['pid', 'name', 'username', 'status']):

    #print(proc.info)

    if  proc.info['name'] == 'GERENCIADORTAREFAA_0002_0005_0307.EXE':         # 'chrome.exe': ; 'GERENCIADORTAREFAA_0002_0005_0307.EXE': ; 'pycharm64.exe': ; 'sisloga_0002_0005_1583.EXE':

        validacao_processo = True
        pid_number = proc.info['pid']

        p = psutil.Process(pid = pid_number)
        with p.oneshot():

            status = p.status()                                                                                     # Status do processo
            memory_uses = str(round(p.memory_percent(memtype='rss') + p.memory_percent(memtype='vms'), 2))          # Uso da memoria pelo processo
            memory_porcentagem_uses = str(psutil.virtual_memory().percent)                                          # Porcentagem total da memoria usada
            cpu_uses = str(sum(p.cpu_times()[:2]))                                                                  # Porcentagem total da CPU pelo processo
            cpu_freq = str(round(psutil.cpu_freq().current / 1000, 1))                                              # Frequencia da CPU

            print(proc.as_dict(attrs=['status']))
            print(proc.as_dict(attrs=['pid']))
            print(proc.as_dict(attrs=['name']))
            print(datetime.now().strftime('%d/%m/%Y %H:%M:%S'))

            # print(pid_number)
            # print(proc.info['name'])
            # print(status)
            # print(memory_uses)
            # print(memory_porcentagem_uses)
            # print(cpu_uses)
            # print(cpu_freq)

            if status != 'running':

                subject = 'Attention - Gerenciador de Tarefas'
                msg = 'Hello Word! \n\n' \
                      '\n' \
                      'The ESL - Gerenciador de Tarefas isn`t running, please check it. ' \
                      '\n\n\n' \
                      'More information about it:' \
                      '\n\n' \
                      f'- PID: {str(pid_number)} \n- Process ' + proc.info['name'] +' \n- Status: ' + status + ' \n- Memory Usage: ' + memory_uses + \
                      '%\n- Total Memory Usage: ' + memory_porcentagem_uses + '%\n- CPU Usage: ' + cpu_uses + ' \n- Frequencia CPU: ' + cpu_freq + 'GHz\n- Log: ' + TC_Email.status_email + ' - ' + datetime.now().strftime('%d/%m/%Y %H:%M')

                #TC_Email.send_email(subject, msg)

                arquivo_log = open('log.txt', 'a')
                arquivo_log.writelines('\nPID: ' + str(pid_number) +'          Process ' + proc.info['name'] +'          Status: ' + status + '          Memory Usage: ' + memory_uses + \
                                       '%          Total Memory Usage: ' + memory_porcentagem_uses + '%          CPU Usage: ' + cpu_uses + '%          Frequencia CPU: ' + cpu_freq + 'GHz          Log: ' + TC_Email.status_email + ' - ' + datetime.now().strftime('%d/%m/%Y %H:%M'))
                arquivo_log.close()

                break

            else:

                arquivo_log = open('log.txt', 'a')
                arquivo_log.writelines('\nPID: ' + str(pid_number) +'          Process ' + proc.info['name'] +'          Status: ' + status + '          Memory Usage: ' + memory_uses + \
                                       '%          Total Memory Usage: ' + memory_porcentagem_uses + '%          CPU Usage: ' + cpu_uses + '%          Frequencia CPU: ' + cpu_freq + 'GHz          Log: ' + TC_Email.status_email + ' - ' + datetime.now().strftime('%d/%m/%Y %H:%M'))
                arquivo_log.close()

                break


if validacao_processo == False:

    memory_porcentagem_uses = str(psutil.virtual_memory().percent)              # Porcentagem total da memoria usada
    cpu_uses = str(sum(psutil.cpu_times()[:2]))                                 # Porcentagem total da CPU pelo processo
    cpu_freq = str(round(psutil.cpu_freq().current / 1000, 1))                  # Frequencia da CPU

    subject = 'Attention - Gerenciador de Tarefas'
    msg = 'Hello Word! \n\n' \
          '\n' \
          'The ESL - Gerenciador de Tarefas isn`t task fould, please check it. ' \
          '\n\n\n' \
          'More information about it:' \
          '\n\n' \
          '- Process: GERENCIADORTAREFAA_0002_0005_0307.EXE' + '%\n- Total Memory Usage: ' + memory_porcentagem_uses + '%\n- CPU Usage: ' + cpu_uses + \
          '%\n- Frequencia CPU: ' + cpu_freq + '%\n- Log: ' + TC_Email.status_email + ' - ' + datetime.now().strftime('%d/%m/%Y %H:%M')

    #TC_Email.send_email(subject, msg)

    arquivo_log = open('log.txt', 'a')
    arquivo_log.writelines('\nTotal Memory Usage: ' + memory_porcentagem_uses + '%          CPU Usage: ' + cpu_uses + '          Frequencia CPU: ' + cpu_freq + '          Log: ' + TC_Email.status_email + ' - ' + datetime.now().strftime('%d/%m/%Y %H:%M'))
    arquivo_log.close()

    print('- Frequencia CPU: ' + cpu_freq + ' GHz \n- Consumo Memoria: ' + memory_porcentagem_uses + '\n- Consumo CPU: ' + cpu_uses)
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.