python-3.xsubprocessatexit

subprocess.Popen batch file wont delete on force terminate


I want to run a batch file using subprocess.Popen … then delete the batch file if I force exit (the red square STOP button in pycharm)

with open('test.bat', "w", encoding='utf-8') as a: a.write('pause')
try:
    SW_HIDE = 1
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW
    info.wShowWindow = SW_HIDE
    p1 = subprocess.Popen('test.bat', startupinfo=info, creationflags=CREATE_NEW_CONSOLE)
    p1.wait()
except KeyboardInterrupt:
    os.remove('test.bat')
finally:
    os.remove('test.bat')

How should this be done? Im running threads so when I force close the program during testing … there are 5+ batch files sitting in my project directory. How can I delete them when exiting the program?


Solution

  • Edit

    Here is my current final working solution

    p1 = None
    SW_HIDE = 1
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW
    info.wShowWindow = SW_HIDE
    p1 = subprocess.Popen('test.bat', startupinfo=info, creationflags=CREATE_NEW_CONSOLE)
    print(f"Subprocess started with PID: {p1.pid}")
    try:
        while p1.poll() is None: time.sleep(0.5)
    except KeyboardInterrupt:
        print('program ended')
        p1.terminate(); p1.wait()
        os.remove('test.txt')
        quit()
    
    print('continue code')
    os.remove('test.txt')
    

    Here is the first rough draft

    
    def cleanup():
        if p1:
            print("Terminating subprocess...")
            p1.terminate()
            p1.wait()
            print("Subprocess terminated.")
            os.remove('test.bat')
    
    p1 = None
    atexit.register(cleanup)
    SW_HIDE = 1
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW
    info.wShowWindow = SW_HIDE
    p1 = subprocess.Popen('test.bat', startupinfo=info, creationflags=CREATE_NEW_CONSOLE)
    print(f"Subprocess started with PID: {p1.pid}")
    
    try:
        while True:
            time.sleep(1)
            if p1.poll() is not None: break
    except KeyboardInterrupt:
        print("Program interrupted by user.")
    finally:
      print("Exiting program...")
    

    and here is the original source code, from google AI

    import atexit
    import subprocess
    import time
    import os
    
    process = None
    
    def cleanup():
        global process
        if process:
            print("Terminating subprocess...")
            process.terminate()
            process.wait()
            print("Subprocess terminated.")
    
    atexit.register(cleanup)
    
    try:
        print("Starting subprocess...")
        process = subprocess.Popen(["sleep", "10"])
        print("Subprocess started.")
        time.sleep(5)
        print("Main process is done.")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        print("Exiting main process.")