0

I have a python script that collect data from a database every minutes by timestamp.

Every minutes this script collect data from a given table in DB by that match the current time with a dely of 1 minutes:

For example at ' 216-04-12 14:53 ' the script will look for data that match ' 216-04-12 14:52 ' in the DB and so on...

Now I want the script to save the last timestamp it collected from the data base before exiting and that for any type of exit (keyboard interrupt, system errors, data base points of failure etc.)

Is there a simple way to do what I want knowing that I can't modify the dataBase

timgeb
  • 76,762
  • 20
  • 123
  • 145
farhawa
  • 10,120
  • 16
  • 49
  • 91
  • Can you modify the script? – syntonym Apr 12 '16 at 15:18
  • Yes of course :confused: – farhawa Apr 12 '16 at 15:18
  • you could use a context manager – timgeb Apr 12 '16 at 15:19
  • 2
    You could look [Exit Handlers](https://docs.python.org/2/library/atexit.html) - `atexit.register()` – AChampion Apr 12 '16 at 15:21
  • Could you clarify how robust this must be? `atexit` module in the standard library is the obvious candidate but it will not run on an `os._exit` or a system error like a power failure, BSOD, or PANIC. For those you will have to save each timestamp, overwriting the previous and making sure the buffers are flushed (like a commit). – cdarke Apr 12 '16 at 15:26
  • Does this answer your question? [Doing something before program exit](https://stackoverflow.com/questions/3850261/doing-something-before-program-exit) – e_i_pi Nov 01 '22 at 00:29

2 Answers2

1

Python's atexit module may help you here. You can import atexit and register functions to run when the program exits.

See this post, namely:

import atexit

def exit_handler():
    print 'My application is ending!'

atexit.register(exit_handler)

That will work in most exit situations.

Another, more robust answer from that same thread:

def main():
    try:
        execute_app() # Stuff that happens before program exits
    finally:
        handle_cleanup() # Stuff that happens when program exits

if __name__=='__main__':
    main()

The above is a bit more reliable...

The MOST reliable way would be to write your output every minute, each time overwriting the previous output. That way no matter whether your exit cleanup fires or not, you still have your data from the minute the program exited.

Community
  • 1
  • 1
Ryan Schuster
  • 494
  • 4
  • 15
0

You could use atexit.register() from module atexit to register cleanup functions. If you register functions f, g, h in that order. At program exit these will be executed in the reverse order, h, g, f.

But one thing to note: These functions will be invoked upon normal program exit. Normal means exits handled by python. So won't work in weird cases.

C Panda
  • 3,297
  • 2
  • 11
  • 11