How to Close a program using python?

前端 未结 6 1554
小鲜肉
小鲜肉 2020-12-05 05:27

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.

6条回答
  •  被撕碎了的回忆
    2020-12-05 05:34

    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

    EDIT: os.kill(pid) is "overkill". process has a kill() method, so:

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

提交回复
热议问题