panchanan
panchanan

Reputation: 192

How to kill process by name in python

>>> os.system('adb shell pidof logcat')

750 4774

0
>>> os.system('adb shell ps | grep logcat')

root      750   1     8760   1720  __skb_recv 7f8f5a5edc S /system/bin/logcat

root      4774  4681  8708   1696  __skb_recv 7f98efeedc S logcat

There are 2 process of logcat. How to kill both process Id : 750 4774

Upvotes: 1

Views: 11064

Answers (3)

legel
legel

Reputation: 2673

Introducing what I like to call kill.py

import psutil

command_substring_to_purge = "app.py"
pids_to_kill = []
processes = psutil.process_iter(attrs=["pid", "cmdline"])

for process in processes:
    pid = process.info["pid"]
    for subcommands in process.info["cmdline"]:
        if command_substring_to_purge in subcommands:
            pids_to_kill.append(pid)
            break

for pid in pids_to_kill:
    process = psutil.Process(pid)
    process.terminate()

Note that to kill root programs you will need to run this as a root.
With great power comes great responsibility.

Upvotes: 0

Abhishek Chandel
Abhishek Chandel

Reputation: 1354

you can try psutil

import psutil

PROC_NAME = "abc.exe"

for proc in psutil.process_iter():
    # check whether the process to kill name matches
    if proc.name() == PROC_NAME:
        proc.kill()

Upvotes: 9

John Zwinck
John Zwinck

Reputation: 249133

import subprocess
subprocess.call(['taskkill.exe', '/IM', 'logcat'])

You might need to use shell=True if it can't find taskkill.exe.

Upvotes: 3

Related Questions