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?

I think your problem is that you are trying to do it in Windows. As I learned recently from another thread, p.wait() sends your win process to some nirvana where it really stops reacting to common events. What I suggested there I suggest here as well: try replacing p1.wait() with while p1.wait(1) is None: pass and see if it works around the issue of not being able to interrupt.

Answering your q more directly: you probably request process kill by clicking pycharm button twice. Kill is a kill: it cannot and will not execute the finally: block.

I tried your code, replacing p1.wait() with while p1.wait(1) is None: pass but this throws an error …subprocess.TimeoutExpired: Command 'test.bat' timed out after 1 seconds … It does not actually catch the end of the program or task … is only deletes the file after 1 second (if I include the finally: statement) and throws this exception after 1 second

Here is an article that suggests this might be an enhancement feature.

This is my current solution. Its working now.

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