JavaSa JavaSa - 2 months ago 20
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

test.py
and the grep's pid itself, in case we are using something like
ps -ef |grep


I think I can use something like
pgrep
python to ignore the grep process, but how do I also exclude the
test.py
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 test1.py
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.

EDIT:
I need this command to be valid through python's
subprocess
module

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


k.wait()

Answer

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 test.py from the commands and finally pipe it to xargs kill:

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