2011-04-11 832 views
8

python可以關閉windows應用程序嗎?我知道如何啓動一個應用程序,但現在我需要知道如何關閉它。如何使用python關閉程序?

+0

你的意思是什麼樣的應用?一個python應用程序?外部? – Stedy 2011-04-11 18:13:53

+0

@Stedy Firefox,我使用python每2小時打開一個網頁,我需要在5分鐘後關閉該頁面。 – acrs 2011-04-11 18:18:44

+0

@Stedy外部一個 – acrs 2011-04-11 18:34:16

回答

9
# 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) 
+0

這工作,但我得到__Access denied__。我正在使用Windows。 – Nabin 2017-06-15 14:30:48

5

如果您使用的是Popen,您應該可以使用send_signal(SIGTERM)terminate()終止應用程序。

See docs here.

1

在Windows中,你可以使用taskkillsubprocess.call:與psutil(當然,對於Linux

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

清潔/更便攜的解決方案你必須丟掉.exe部分使用.startwith("firefox")

import psutil,os 
for pid in (process.pid for process in psutil.process_iter() if process.name()=="firefox.exe"): 
    os.kill(pid) 

,將殺死命名爲firefox.exe所有進程

編輯:os.kill(pid)是 「大材小用」。 processkill()方法,所以:

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