Search code examples
pythonlinuxtop-command

how to get all process information in linux?


I want to get all process information in a linux server.
PID, USER, CPU% , COMMAND ...
Exactly, I want to get these information in a python script. I tried
a,b = commands.getstatusoutput('top -n 1')
This gave me about 20 rows of results ordered by CPU%, but I want more, about 40 or 50 rows of results.

How should I do?

I use psutil as follow, for each proc, it need to wait 1 second. How can I get cpu_percent like top command quickly.

for proc in psutil.process_iter():
    try:
        pinfo = proc.as_dict(attrs=['pid', 'username', 'cpu_percent', 'name'])
        pinfo['cpu_percent'] = proc.cpu_percent(interval=1)
        if pinfo['cpu_percent'] > 0:
            print(pinfo)
        except psutil.NoSuchProcess:
            pass

Solution

  • I recommend you using psutil library like what zenlc2000 said in his comment. However, you can use the output of top's command.

    You have also to take a look at top command's manual or simply writing man top in your terminal.

    I give you an example of using top command's output within Python3 (or Python2):

    Let's suppose i want to know top command's output for gedit:

    $ top -b n 1 | grep gedit
    

    Output:

    8381 nexus   20   0  565928  43696  30268 S   0,0  1,1   0:06.03 gedit
    

    In order to understand the output i'll write it with the keys:

     PID  UTIL     PR    NI    VIRT     RES    SHR   S  %Cpu %MEM TEMPS+   COM.
     8381 nexus    20    0     565928   43696  30268 S  0,0  1,1  0:06:03  gedit
    

    Now, we'll filer the output with awk:

    $ echo -n "%CPU: " && top -b n 1 | grep gedit | awk '{print $9}'
    

    Output:

    %CPU: 0,0
    

    Or simply:

    $ top -b n 1 | grep gedit | awk '{print $9}'
    

    Output:

    0,0
    

    Using Python3 (or any version you want) in your terminal:

    $ python3
    >>> import subprocess
    >>> proc = subprocess.Popen("top -b n 1 | grep gedit | awk '{print $9}'", shell = True, stdout=subprocess.PIPE)
    >>> p = proc.communicate()
    >>> p[0].decode("utf8").replace("\n","")
    

    Output:

    0,0
    

    And here you go! You got gedit process percentage using Python3 and the output of top command.

    You can repeat this process to get all the informations you want from top's output.