How to implement a persistent counter in Python -


Is there a way of "last known counter" in Python that will survive after a server reboot?

I have a dragon script, which is launched by the schedule (by the cron). It reads the files with the document ID in the predefined format. If any, I have to remember the last documented document id to ignore all the previous ones.

Any value you want to save from reboots should be constantly put in storage - i.e. Disc. It means any kind of file, even if it's a simple plain text file or database file that is up to you, you have indicated in the comments that you do not think it's a "cross-platform" but it will be a really funny platform That it does not have some type of file system support.

If you have built-in SQLite support for structured storage then with Python module, it seems that you need to store a single ID, so a simple file will be sufficient. I give some suggestions like this:

  import os DATA_FILENAME = os.path.expanduser ("~ / document-counter.txt") def update_document_id (new_id): with opening (DATA_FILENAME , "W") as FD: fd.write (new_id + "\ n") def recover_document_id (): with open (DATA_FILENAME, "r") fd: return fd.readline (). Strip ()   

You should probably check for a better error (for example, if the file does not exist, grab the exception), but it shows you how simple the solution can be You are better than catching exceptions (often often considered more pyothic) but if you want to test clearly, then it is to say that the existence of the file is portable easily:

  No OS .path.exists (DATA_FILENAME): Print "A Can not find e-file. To deal with it. "   

If you need to add more data fields later, then I suggest sucliite - it is convenient, strong and allows you to interoperate with applications in other languages. So that it is needed in the future. In addition you can use the standalone SQLite command line client to manipulate your data if you only need it, you only provide a file name for the sqlite3.connect () method, so This is essentially an easy to open a file, just you can break it on SQL.

However, I simply paste a simple single id in a plain-word file - you are not actually more compatible with it.

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -