Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Close a program using python?

Tags:

python

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.

like image 248
acrs Avatar asked Apr 11 '11 18:04

acrs


People also ask

What does exit () do in Python?

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.


2 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) 
like image 140
gh057 Avatar answered Oct 13 '22 18:10

gh057


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() 
like image 22
Jean-François Fabre Avatar answered Oct 13 '22 19:10

Jean-François Fabre