如何使用python关闭程序?

acr*_*crs 15 python

有没有办法python可以关闭Windows应用程序?我知道如何启动应用程序,但现在我需要知道如何关闭它.

小智 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)

  • 这有效,但我得到 __Access denied__。我正在使用窗户。 (2认同)

Jea*_*bre 7

在 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)


Dem*_*cht 5

如果你使用Popen,你应该能够终止使用任何应用程序send_signal(SIGTERM)terminate().

请参阅此处的文档.