Part of my code deals with terminating a process with a user input using Window's command prompt. Here's a snippet from my project.
import subprocess
def kill_process():
# Displays running processes similar to linux 'top' command.
subprocess.call(['tasklist'])
cmd = input('\nEnter process name or process ID to kill process: ')
try:
# Kills process via user input.
subprocess.call(['taskkill', '/pid', cmd])
except:
print('Invalid process name or ID.\n')
kill_process()
If the user enters an invalid process name or ID I get this error:
ERROR: The process "user_input" not found.
I believe this error isn't handled by python, but rather by Windows. Therefore, I can't catch the exception and handle it accordingly. When this error is raised it forces my code to exit, which is an issue because I need the code to continue, even threw user error.
I can parse threw the data and get process names / IDs using subprocess.check_output() with something like this;
cmd = input('\nEnter process name or process ID to kill process: ')
if cmd in subprocess.check_output(['tasklist'], encoding='UTF-8'):
subprocess.call(['taskkill', '/pid', cmd])
but, if possible, I rather avoid this method. I might run into similar errors when dealing with CMD later down the line and parsing through this type of data can become tedious.