Python to close windows application process

When automating some tasks in Windows OS, you may wonder how to automatically close the application if you do not have the direct control of the running application or when the application is just running for too long time. In this article, I will be sharing with you how this can be achieved with some python library, to be more specific, the win32com library.

Prerequisites

You will need to install the pywin32 library if you have not yet installed:

Find the application name from Windows Task Manager

You will need to first find out the application name which you intend to close, the application name can be found from the Windows task manager. E.g. If you expend the “Windows Command Processor” process, you can see the running application name is “cmd.exe”.

Image for post

Let’s get started with the code!

Import the below modules that we will be using later:

from win32com.client import GetObject 
from datetime import datetime
import os

And we need to get the WMI (Windows Management Instrumentation) service via the below code, where we can further access the window processes. For more information about WMI, please check this.

WMI = GetObject('winmgmts:')

Next, we will use the WMI SQL query to get the processes from the Win32_Process table by passing in the application name. Remember we have already found the application name earlier from the task manager.

for process in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'): 
#the date format is something like this 20200613144903.166769+480 create_dt, *_ = process.CreationDate'.split('.')
diff = datetime.now() - datetime.strptime(create_dt,'%Y%m%d%H%M%S')

There are other properties such as Description, Status, Executable Path, etc. You can check the full list of the process properties from this Windows documentation. Here we want to base on the creation date to calculate how much time the application has been running to determine if we want to kill it.

Assuming we need to kill the process after it’s running for 5 minutes.

if diff.seconds/60 > 5: 
print("Terminating PID:", process.ProcessId')
os.system("taskkill /pid "+str(process.ProcessId))

With this taskkill command, we will be able to stop all the threads under this process peacefully.

Conclusion

The win32com is super powerful python library especially when dealing with the Windows applications. You can use it to read & save attachments from outlook, send emails via outlook , open excel files and some more. Do have a check on these articles.

As per always, welcome any comments or questions.

Originally published at https://www.codeforests.com on July 4, 2020.

Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store