简体   繁体   中英

Killing a process based on how long it as been running with psutil Python

I am running a lot of processes called "csm.py". Each process has a command line argument for example "testarg".

"csm.py testarg".

I am using psutil to sucessfully check if another process of the same name ("csm.py testarg") is running with this code:

for process in psutil.process_iter():
        cmdline = process.cmdline
        if result[0][2] in cmdline:
            proc += 1
        if proc >= 2:
            # DO SOMETHING

What I would like to do is find out IF there is a process called "csm.py testarg" already running that is older than 1 hour, and if it is kill it but do not kill the new process (this one) that is checking for the old "csm.py testarg". Is it possible to get the processes start time / date with psutil?

Thanks

I managed to figure it out like so:

for process in psutil.process_iter():
    pid = process.pid
    cmdline = process.cmdline
    if what_im_looking_for in cmdline:
        p = psutil.Process(pid)
        p.create_time
        pidcreated = datetime.datetime.fromtimestamp(p.create_time)
        allowed_time = pidcreated + datetime.timedelta( 0, 5400 )
        now = datetime.datetime.now()
        if now > allowed_time:
            print "Killing process {} Start time: {} Current time: {}".format( pid, pidcreated, now)
            p.kill()
>>> import os, psutil, datetime
>>> p = psutil.Process(os.getpid())
>>> p.create_time()
1307289803.47
>>> datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S")
'2011-03-05 18:03:52'

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