How to close a program using python?

Is there a way python can close a windows application? I know how to start the application, but now I need to know how to close it.

+8
python
source share
4 answers
# 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) 
+9
source share

If you use Popen , you can terminate the application using send_signal(SIGTERM) or terminate() .

See documents here

+5
source share

You probably want to use os.kill http://docs.python.org/library/os.html#os.kill

+1
source share

in windows you can use taskkill inside subprocess.call :

 subprocess.call(["taskkill","/K","/IM","firefox.exe"]) 

A clean / more portable solution with psutil (well, for Linux you need 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) 

which will kill all processes named firefox.exe

EDIT: os.kill(pid) is "redundant." process has a kill() method, therefore:

 for process in (process for process in psutil.process_iter() if process.name()=="firefox.exe"): process.kill() 
+1
source share

All Articles