小智 17
# 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)
Run Code Online (Sandbox Code Playgroud)
在 Windows 中,您可以taskkill在以下范围内使用subprocess.call:
subprocess.call(["taskkill","/F","/IM","firefox.exe"])
Run Code Online (Sandbox Code Playgroud)
/F强制进程终止。省略它只会要求关闭 Firefox,如果应用程序响应,它可以工作。
更清洁/更便携的解决方案psutil(好吧,对于 Linux,您必须删除该.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)
Run Code Online (Sandbox Code Playgroud)
这将杀死所有命名的进程 firefox.exe
顺便说一句os.kill(pid)是“矫枉过正”(没有双关语意)。process有一个kill()方法,所以:
for process in (process for process in psutil.process_iter() if process.name()=="firefox.exe"):
process.kill()
Run Code Online (Sandbox Code Playgroud)