Created
April 3, 2022 20:23
-
-
Save AykutSarac/fb911f728432c556ca89b73e3d311d26 to your computer and use it in GitHub Desktop.
Beautiful Python Task Manager CLI
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
from InquirerPy import prompt | |
import os | |
import psutil | |
customStyle = { | |
"question": "#cc00ff bold", | |
"pointer": "#ff9d00", | |
"answer": "#39a7e6 bold", | |
"fuzzy_match": "#2cf56c bold", | |
} | |
def getProcessList(): | |
ppids = set() | |
listOfProcessNames = list() | |
# Iterate over all running processes | |
for proc in psutil.process_iter(): | |
# Get process detail as dictionary | |
pInfoDict = proc.as_dict(attrs=['pid', 'name', 'ppid']) | |
hasProcess = pInfoDict.get('ppid') in ppids | |
if not hasProcess: | |
# Append dict of process detail in list | |
listOfProcessNames.append(pInfoDict) | |
# Filter by parent process to prevent duplicates | |
ppids.add(pInfoDict.get('ppid')) | |
return listOfProcessNames | |
def confirmBack(): | |
answers = prompt({ | |
'type': 'list', | |
'name': 'quit', | |
'message': 'Are you sure you want to quit?', | |
'choices': ['Go Back', 'Quit'] | |
}, style={ | |
**customStyle, | |
"question": "#70a9ff", | |
"pointer": "#ff6600" | |
}) | |
# Handle quit | |
if answers['quit'] == 'Go Back': | |
getPrompt() | |
else: | |
quit() | |
def confirmKill(process): | |
answer = prompt({ | |
'type': 'confirm', | |
'name': 'confirm_kill', | |
'message': 'Are you sure you want to kill this process?', | |
}, style=customStyle) | |
# Get process from prompt answer | |
val = next((x for x in getProcessList() if process == x.get('name')), None) | |
# Handle process | |
if answer['confirm_kill'] == True: | |
os.kill(val.get('ppid'), 9) | |
print('\nProcess killed successfully!\n') | |
confirmBack() | |
else: | |
confirmBack() | |
# Main app | |
def getPrompt(): | |
# Define process list | |
processList = map(lambda val: val.get('name'), getProcessList()) | |
answer = prompt({ | |
'type': 'fuzzy', | |
'name': 'process', | |
'message': 'Choose a process to kill:', | |
'choices': processList, | |
'mandatory': False | |
}, | |
style=customStyle, | |
raise_keyboard_interrupt=False | |
) | |
# Check User Response | |
if answer['process'] == None: | |
confirmBack() | |
else: | |
confirmKill(answer['process']) | |
# Run Task Manager | |
getPrompt() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment