JavaSa JavaSa - 1 year ago 91
Bash Question

Killing all python scripts except one python script and the grep process

How can I run command in bash to kill all python scripts except script called
and the grep's pid itself, in case we are using something like
ps -ef |grep

I think I can use something like
python to ignore the grep process, but how do I also exclude the
script? I know there is an option to do grep -v, is there option to do
pgrep -v

Clarification: except grep process- means when we do for example
ps -ef |grep
we get also the grep pid that used to bring this result. I don't want to kill it as this process is no longer exist in the stage that results are shown.

I need this command to be valid through python's

k = subprocess.Popen('[some_bash_cmd_here]',shell=True)


Answer Source

You can use pgrep -fl python to get all the commands matching python then get it piped with awk to get the process id by excluding from the commands and finally pipe it to xargs kill:

pgrep -fl python | awk '!/test\.py/{print $1}' | xargs kill