How to close an executable on Python like clicking on exit button

682 views Asked by At

I will explain my problem :

For an application for my system I would like to know how to close an executable, like clicking on the pushbutton exit in the top rigth, as usual. Context : From a script python, I would like to run an executable. It is works fine with os.system or subrpocess popen. Moreover, I would like to know when this executable is close, it's works fine with subprocess check output. And my problem : I would like to close the executable that I ran, but for many reasons on my system (the .exe send an snmp messages when it is closed by the button "close" in the top right to an another script, I can't change that), I have to close this executable as if I close manually the executable window.

To do self.p.terminate did'nt works.

Please, if you have any ideas, tell me. Thanks for your answer, Have a good day

My code is below :

import subprocess
import os
import sys,string,os
import threading 
import time 

class test():
    
    def __init__(self):
        pass
        
    def lancement(self):
        os.chdir('C:\dossier')
        self.p = subprocess.Popen("C:\dossier\TEST.exe")
        self.id = self.p.pid
        #os.system("C:\dossier\TEST.exe")
        
    def verification(self):
        while True :
            
            self.s = subprocess.check_output('tasklist', shell = True)
            
            if b"TEST.exe" not in self.s :
                print('Absent')
                
                break
            
            else : 
                print('toujours present')

    def fermeture(self):

        #os.close("C:\dossier\TEST.exe")
        #self.p.terminate()
        os.kill(self.id,signal.SIGTERM)
    def tests(self):
        ouais = threading.Thread(target =self.lancement)
        ouais.start()
        time.sleep(2) 
        testverif = threading.Thread(target = self.verification)
        testverif.start()
        time.sleep(20) 
        self.fermeture()
 
def main():
    testa = test()
    testa.tests()
main()
1

There are 1 answers

1
Faraaz Kurawle On BEST ANSWER

You can use os modules for this.

os.system("taskkill Test.exe")

This would gently Kill the application.

taskkill is a cmd command which helps you to Kill process. os.system() method execute the command (a string) in a subshell/cmd.

Also check the taskkill docs of further parameter if needed.