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

1
  • not really a python question...more unix/shell Commented Apr 24, 2020 at 7:17

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

yeah i know that but. i wanted to know if there is a way to kill the process using program name
@sharath updated the answer with the program name ;)
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!

2 Comments

no i also tried this. pkill python3 kills all programs but pkill program1.py doesnt kill the process.
when i looked for pgrep -l python i got all process but pgrep -l program1.py didnt give a output.
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?

Comments

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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.