How to Close a program using python?

前端 未结 6 1533
小鲜肉
小鲜肉 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()
    
    0 讨论(0)
  • 2020-12-05 05:38
    # 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 讨论(0)
  • 2020-12-05 05:40

    If you're using Popen, you should be able to terminate the app using either send_signal(SIGTERM) or terminate().

    See docs here.

    0 讨论(0)
  • 2020-12-05 05:52

    In order to kill a python tk window named MyappWindow under MS Windows:

    from os import system
    system('taskkill /F /FI "WINDOWTITLE eq MyappWindow" ')
    

    stars maybe used as wildcard:

    from os import system 
    system('taskkill /F /FI "WINDOWTITLE eq MyappWind*" ')
    

    Please, refer to "taskkill /?" for additional options.

    0 讨论(0)
  • 2020-12-05 05:54

    On OS X:

    1. Create a shell script and put:
    killall Application
    

    Replace Application with a running app of your choice.

    In the same directory as this shell script, make a python file. In the python file, put these two lines of code:

    from subprocess import Popen
    Popen('sh shell.sh', shell=True)
    

    Replace shell.sh with the name of your created shell script.

    0 讨论(0)
  • 2020-12-05 05:57

    You want probably use os.kill http://docs.python.org/library/os.html#os.kill

    0 讨论(0)
提交回复
热议问题