I am trying to run code when my script is closed.
def main():
atexit.register(disconnect)
try:
do_something()
while True:
os.system('cls')
print("Something")
time.sleep(15)
finally:
disconnect()
if __name__=='__main__':
main()
When run from a console with python myscript.py and terminating the script with Strg+C the finally block and atexit function is run and the disconnect function does its job.
Now I want the same behavior in an .exe file. I use pyinstaller myscript.py --onefile.
Wenn closing the console window that opens during normal program operation, the finally block and the function registered with atexit are not executed.
I tried switching from the finally block to the atexit module. I expect I am missing something to do with how the exe is started and what closing the windows actually means in that context, but I could not find any more information.