Linux script to get most expensive processes

Cecil Westerhof Cecil at
Tue Aug 4 22:19:31 CEST 2015

Under Linux I like to get the most expensive processes. The two most
useful commands are:
    ps -eo pid,user,pcpu,args --sort=-pcpu
    ps -eo pid,user,pcpu,args --sort=-vsize

In my case I am only interested in the seven most expensive processes.
For this I wrote the following script.

#!/usr/bin/env python3

import subprocess
import sys

def give_output(param):
    output = subprocess.check_output(([
        '--columns={0}'               .format(max_line_length),
        '--sort=-{0}'                 .format(param)
    for line in output[:no_of_lines]:

accepted_params     = {
current_platform    = sys.platform
max_line_length     = 200
needed_platform     = 'linux'
no_of_lines         = 8                     # One extra for the heading

if current_platform != needed_platform:
    raise Exception('Needs a {0} platform, got {1} platform'.
                    format(needed_platform, current_platform))
no_of_parameters = len(sys.argv) - 1
if no_of_parameters == 0:
    to_check = 'pcpu'
elif no_of_parameters == 1:
    to_check = sys.argv[1]
    raise Exception('Too many arguments')

if (to_check != 'all') and not(to_check in accepted_params):
    raise Exception('Used illegal parameter: {0}'.format(to_check))

if to_check == 'all':
    for param in sorted(accepted_params):

Is this a reasonable way to do this? Getting the parameter is done
quit simple, but I did not think fancy was necessary here.

Cecil Westerhof
Senior Software Engineer

More information about the Python-list mailing list