I try to develop Task manager for my personal use using python3. In my code I use this command to list all running process in a while loop

ps -eo pid,comm,user,%mem,%cpu | awk '{$4=<Variablehere>*$4/100;}{print;}'

but each time it is executed there are three processes I don't want them to be listed which are sh ps awk

so my question is, how can I get the PIDs of these processes so that I can later get rid of them from the list



import subprocess
from time import sleep

class processData : def init (self) : mem = next(self._run_command("m")).decode('utf-8').replace("\n","") mem = str(int(float(mem)/1024)) #print(mem)

self.allprocess = "ps -eo pid,comm,user,%mem,%cpu | awk '{$4="+mem+"*$4/100;}{print;}';" self.ownprocess = "ps -eo pid,comm,user,%mem,%cpu | awk '{$4=(" + mem + "*$4/100);}{print;}' | grep $USER" self.otherprocess = "ps -eo pid,comm,user,%mem,%cpu | awk '{$4=(" + mem + "*$4/100);}{print;}' | grep -v $USER" def _run_command(self,fil): if fil == "a" : command = self.allprocess elif fil == "u" : command = self.ownprocess elif fil == "o" : command = self.otherprocess elif fil == "m" : command = "awk '/MemTotal/ {print $2}' /proc/meminfo" p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) for line in iter(p.stdout.readline, b''): if line: yield line while p.poll() is None: sleep(.1) err = p.stderr.read() if p.returncode != 0: print("Error: " + str(err)) @staticmethod def unique(list1 , list2) : ids = [i[0] for i in list2] return [i for i in list1 if i[0] not in ids]; def get(self,choice) : processes = []; for process in self._run_command(choice) : processes.append(process.decode('utf-8').replace("\n","").split()); return processes#[0:(len(processes)-1)-2]; print(processData().get("a"));

What I want is not to list any processes that is running due to the running of my program

  • 1
    Have you considered using one of the existing python APIs such as psutil or proc instead of shelling out to a ps command? Sep 30 '18 at 17:44
  • @steeldriver thanks a lot I will take a look at them Sep 30 '18 at 18:42
  • @steeldriver Please make it an Answer to accept it, it's very useful Sep 30 '18 at 18:53

Just insert the condition $2 !~ /^(awk|sh|ps)$/:

ps -eo pid,comm,user,%mem,%cpu | awk '$2 !~ /^(awk|sh|ps)$/ {$4=<Variablehere>*$4/100;}{print;}'

It means "if $2 does not match start-of-string, followed by either awk, sh, or ps, followed by end-of-string" then ...

  • I don't want to block any sh ps awk , I want to block them in that process using their PIDs thanks for your reply Sep 30 '18 at 15:51
  • 1
    Then swap the condition by replacing !~ with ~.
    – PerlDuck
    Sep 30 '18 at 15:54
  • Please take a look on my question edit Sep 30 '18 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.