Is there a way that python can close a windows application (example: Firefox) ?
I know how to start an app, but now I need to know how to close one.
Python's exit() function is used to exit and come out of the code directly. This function is only used by interpreters and is synonymous with the quit() method. The exit function closes the program with a detailed status.
# I have used os comands for a while # this program will try to close a firefox window every ten secounds import os import time # creating a forever loop while 1 : os.system("TASKKILL /F /IM firefox.exe") time.sleep(10)
in windows you could use taskkill
within subprocess.call
:
subprocess.call(["taskkill","/F","/IM","firefox.exe"])
/F
forces process termination. Omitting it only asks firefox to close, which can work if the app is responsive.
Cleaner/more portable solution with psutil
(well, for Linux you have to drop the .exe
part or use .startwith("firefox")
:
import psutil,os for pid in (process.pid for process in psutil.process_iter() if process.name()=="firefox.exe"): os.kill(pid)
that will kill all processes named firefox.exe
By the way os.kill(pid)
is "overkill" (no pun intended). process
has a kill()
method, so:
for process in (process for process in psutil.process_iter() if process.name()=="firefox.exe"): process.kill()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With