9

I am running on a Linux x86-64 system. From a Python (2.6) script, I wish to periodically check whether a given process (identified by pid) has become "defunct"/zombie (this means that entry in the process table exists but the process is doing nothing). It would be also good to know how much CPU the process is consuming (similar to what 'top' command shows).

Can somebody give me some pointers on how I can get these in Python?

1
  • Run the ps command via subprocess.Popen(). Each line is a process and a Z in the STAT column means you've got a zombie. ps has a ton of parameters (man ps) and can give you a lot of information. Commented Mar 11, 2013 at 18:58

2 Answers 2

27

I'd use the psutil library:

import psutil

proc = psutil.Process(pid)
if proc.status() == psutil.STATUS_ZOMBIE:
    # Zombie process!
Sign up to request clarification or add additional context in comments.

1 Comment

proc.get_cpu_times(), proc.get_cpu_percent(interval=1.0) to get CPU usage.
3

you can get top result in python as below:

linux:

import sys, os
f = os.popen("top -p 1 -n 1", "r")
text = f.read()
print text

update

windows:

from os  import popen
from sys import stdin

ps = popen("C:/WINDOWS/system32/tasklist.exe","r")
pp = ps.readlines()
ps.close()

# wow, look at the robust parser!
pp.pop(0)       # blank line
ph = pp.pop(0)  # header line
pp.pop(0)       # ===

print ("%d processes reported." % len(pp))
print ("First process in list:")
print (pp[0])

stdin.readline()

1 Comment

assuming you are on an os that has it...(which OP is)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.