Shell pipelines through Python subprocess module

So, I am trying to request the “intensive” processes of processor 3 on a given machine, and I found this shell command: ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3

I want to use this data inside a Python script, so I need to be able to output the output of the above command through a module subprocess. The following works, but just returns a huge string, since I do not limit it to the top of 3:

psResult = subprocess.check_output(['ps', '-eo', 'pcpu,user,args'])

I'm not quite sure how this works subprocess.check_output.. in a lean attempt, I tried:

subprocess.check_output(['ps', '-eo', 'pcpu,user,args', '|', 'sort', '-k', '1', '-r', '|', 'head', '-3'])

Which gives me an error: ps: illegal argument: |

How to use pipe symbol |inside Python or use some other way to sort without having to do an incredible amount of parsing on the huge string returned psResult = subprocess.check_output(['ps', '-eo', 'pcpu,user,args'])?

Thank! Regards, -kstruct

+5
4

shell=True :

import subprocess
subprocess.check_output('ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3',
                        shell=True)

ps Python, :

raw = subprocess.check_output('ps -eo pcpu,pid,user,args --sort -pcpu')
first_three_lines = list(raw.split('\n'))[:3]
+10

shell=True, , . shell=True . docs :

output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
+4

, :

subprocess.check_output("ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3", shell=True)

, /bin/sh, .

+1

Why use external commands? Use psutil :

import psutil
def cpu_percentage(proc):
    try:
        return proc.get_cpu_percent()
    except psutil.AccessDenied:
        return float('-inf')

top3 = sorted(psutil.process_iter(), key=cpu_percentage, reverse=True)[:3]
for proc in top3:
    # do whatever
+1
source

All Articles