0

when i use ps -ef |grep i get the current running programs if below shown are the currently running programs.How can i stop a program using the name of the program

user   8587  8577 30 12:06 pts/9    00:03:07 python3 program1.py

user   8588  8579 30 12:06 pts/9    00:03:08 python3 program2.py

eg. If i want to stop program1.py then how can i stop the process using the program name "program1.py" .If any suggestions on killing the program with python will be great

sharath
  • 51
  • 5

4 Answers4

1

By using psutil is fairly easy

import psutil

proc = [p for p in psutil.process_iter() if 'program.py' in p.cmdline()]
proc[0].kill()

To find out the process from the process name filter through the process list with psutil like in Cross-platform way to get PIDs by process name in python

pna
  • 5,651
  • 3
  • 22
  • 37
1

Try doing this with the process name:

pkill -f "Process name"

For eg. If you want to kill the process "program1.py", type in:

pkill -f "program1.py"

Let me know if it helps!

Viktor1903
  • 359
  • 1
  • 4
  • 18
  • no i also tried this. pkill python3 kills all programs but pkill program1.py doesnt kill the process. – sharath Apr 24 '20 at 07:09
  • when i looked for pgrep -l python i got all process but pgrep -l program1.py didnt give a output. – sharath Apr 24 '20 at 07:22
0

Assuming you have pkill utility installed, you can just use:

pkill program1.py

If you don't, using more common Linux commands:

kill $(ps -ef | grep program1.py | awk '{print $2}')

If you insist on using Python for that, see How to terminate process from Python using pid?

Błotosmętek
  • 12,717
  • 19
  • 29
0

grep the program and combine add pipe send the output in another command.
1. see program ps -ef.
2.search program grep program.
3. remove the grep that you search because is appear in the search process grep -v grep.
4.separate the process to kill with awk awk '{ print $2 }' 5. apply cmd on the previous input xarks kill -9

ps -ef  | grep progam | grep -v grep | awk '{ print $2 }' | xargs kill -9

see here for more:
about pipe , awk, xargs

with python you can use os:

template = "ps -ef  | grep {program} | grep -v grep | awk '{{ print $2 }}' | xargs kill -9"
import os
os.system(template.format(program="work.py"))
Beny Gj
  • 607
  • 4
  • 16