Created
May 12, 2021 18:42
-
-
Save ayushxx7/ad0f0ba853e7b95c1d898f127c7c1e8f to your computer and use it in GitHub Desktop.
Kill Process by Name using the `psutil` module in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import traceback | |
import psutil | |
def kill(process_name): | |
"""Kill Running Process by using it's name | |
- Generate list of processes currently running | |
- Iterate through each process | |
- Check if process name or cmdline matches the input process_name | |
- Kill if match is found | |
Parameters | |
---------- | |
process_name: str | |
Name of the process to kill (ex: HD-Player.exe) | |
Returns | |
------- | |
None | |
""" | |
try: | |
print(f'Killing processes {process_name}') | |
processes = psutil.process_iter() | |
for process in processes: | |
try: | |
print(f'Process: {process}') | |
print(f'id: {process.pid}') | |
print(f'name: {process.name()}') | |
print(f'cmdline: {process.cmdline()}') | |
if process_name == process.name() or process_name in process.cmdline(): | |
print(f'found {process.name()} | {process.cmdline()}') | |
process.terminate() | |
except Exception: | |
print(f"{traceback.format_exc()}") | |
except Exception: | |
print(f"{traceback.format_exc()}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment