简体   繁体   中英

How to know a lifetime of a process with Python?

Scenario: I have multiple Firefox browsers open. At somepoint i run my script to shut down all firefox processes that have been up for more than 30minutes.

Im doing this on Windows. Is it possible to get lifetime from a process?

PROCNAME = "firefox.exe"

# Shuts down all PROCNAME processes
for proc in psutil.process_iter():
    if proc.name() == PROCNAME:
        proc.kill()

I just used psutil as Amandan suggested above. I used the PROCNAME "Google Chrome" since that is the browser I'm running and I was able to get the process creation time using the method below.

I assume you can subtract the current time from the process creation time to get the time that the browser has been running.

import psutil
import datetime

PROCNAME = "Google Chrome"

for proc in psutil.process_iter():
    if proc.name() == PROCNAME:
        p = psutil.Process(proc.ppid())
        print(f"Creation time of {PROCNAME} process: ", datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S"))

Output: 在此处输入图片说明

psutil is a really great module to retrieve information for all system processes and it is cross-platform .

psutil doesn't provide information on how long the process has been running, however, it does provide a process creation time, so process running time can be easily figured.

import psutil
import time
PROCNAME = "firefox.exe"
for proc in psutil.process_iter():
      if proc.name() == PROCNAME:
        etime = time.time() - proc.create_time()
        print(etime)
        if(etime > 1800): #30mintues or more running time
          proc.kill()

Another way for Windows :

import os, time, datetime, threading
import subprocess, psutil, statistics

def perf_psutil(n=100):
    liste = []    
    count = 0
    ct = time.time()
    while count < n:
        count+=1
        t0 = time.perf_counter_ns()
        p = [proc.create_time() for proc in psutil.process_iter() if proc.name() == "explorer.exe"][0]
        d = ct - p
        t1 = time.perf_counter_ns()
        liste.append(t1-t0)

    print("Date in sec:",p)
    print("Duration:",d)
    print("Performance psutil :", statistics.mean(liste)/10**9)

def perf_wmic(n=100):
    liste = []    
    count = 0
    ct = datetime.datetime.now()
    while count < n:
        count+=1
        t0 = time.perf_counter_ns()
        p = [x.split(b'CreationDate=')[1] for x in subprocess.Popen('wmic PROCESS WHERE NAME="Explorer.exe" GET * /format:list <nul', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0].replace(b'\r\r\n',b',').split(b',') if x.startswith(b'CreationDate=')][0]
        d = datetime.datetime.now()-datetime.datetime(int(p[:4]),int(p[4:6]),int(p[6:8]),int(p[8:10]),int(p[10:12]),int(p[12:14]),int(p[15:-4]))
        t1 = time.perf_counter_ns()
        liste.append(t1-t0)

    print("Date :",p)
    print("Duration:",d.total_seconds())
    print("Performance wmic :", statistics.mean(liste)/10**9)
          
print('########## PSUTIL ##########')
perf_psutil(10)
print('############################')
print('########### WMIC ###########')
perf_wmic(10)
print('############################')

Results :

########## PSUTIL ##########
Date in sec: 1624790271.081833
Duration: 18625.84829068184
Performance psutil : 0.17050247
############################

########### WMIC ###########
Date : b'20210627123751.081832+120'
Duration: 18628.22999
Performance wmic : 0.06602881
############################

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM