0

I would like to save some variables to pickle file on exit, although closing the program by the user (exit code -1, by pressing the "X" button) do not trigger the .atexit functions.

How can I do this?

  • 2
    how exactly is the user exiting? you can use signals if way of user exit is known. – Pbd Apr 25 '18 at 09:35
  • You can also handle exit signal of the OS. Read [this](https://stackoverflow.com/q/18499497/952747) – masoud Apr 25 '18 at 09:37
  • By closing the program manually ( 'X' button) – Piotr Gołdyś Apr 25 '18 at 09:38
  • 1
    What is the "X button"? Is it of terminal or is it GUI of your program? – abukaj Apr 25 '18 at 09:44
  • My OS is Windows. I'm currently running it in Python - python.exe (or in PyCharm interpreter), although I would like to make a GUI for it someday – Piotr Gołdyś Apr 25 '18 at 09:48
  • Pycharm does not use X button to stop a script. By default at least. It uses `ctrl+F2` to send SIGINT / SIGKILL. – Ivan Vinogradov Apr 25 '18 at 09:51
  • Well, take a look: https://repl.it/@PiotrGoldys/LumberingThoseFunction It saves the data when the program exits by itsef (as specified). I would like to make it save data also when stopped manually, by clicking "stop" – Piotr Gołdyś Apr 25 '18 at 09:53
  • `atexit` will only work if your program exits cleanly. If you stop the interpreter in its tracks they won't be called. It's the interpreter that executes those functions and it can't do that if you have stopped it. You will have to provide a more elegant way to exit your program than simply killing the interpreter process. – BoarGules Apr 25 '18 at 10:03
  • I know that `atexit` won't work in this case. Just wondering if there is some method to handle it, without creating "elegant way to exit program" – Piotr Gołdyś Apr 25 '18 at 10:06
  • I came up with an idea of using threading, to create thread in which I specify, that program will close after some input, lets say "s". How can I make it just "idle" in background and wait for "exit input"? `def out(): if input() == "s": exit() # Exit command which works with `atexit` - didnt check if this command will do it yet t1 = threading.Thread(target=out) t1.start()` Here is what i came up with, although it overrides the whole program and makes it wait for input, instead of toing it in the background – Piotr Gołdyś Apr 25 '18 at 11:13
  • Or maybe it would be better to make a GUI using tkinker and follow with this: https://stackoverflow.com/questions/37764489/detect-when-the-x-or-close-button-is-pressed?rq=1 ? – Piotr Gołdyś Apr 25 '18 at 11:31

0 Answers0