开发者

Python: JobID counter

Whats the best to make a job ID counter in python? For example if a Job ID startd of with value of "0" and everytime someone ran the script the counter went up by one?

E.G.

X = 0

Perform_some_process

x +=1

Now the value of x will be one, but if i ran the script again x will be equal to one again and not two. How would make so when someone开发者_如何学Go ran the script for the second time x is equal to two? and so forth for the future runs.


You need to "persist" that counter -- simplest is to use a file for the purpose. For example:

import os

def onemore():
    f = __file__ + '.counter'
    if os.path.exists(f):
        with open(f) as thefile:
            counter = int(thefile.read())
    else:
        counter = -1
    counter += 1
    with open(f, 'w') as thefile:
        thefile.write(str(counter) + '\n')
    return counter

This could give problems (missing some counts) if multiple instances of the script are starting at exactly the same time -- if that's an issue for you please let us know (and let us know what OS you need to work on) to learn more about how to perform locking on that crucial file.

This solution also assumes that the directory where this Python (or bytecode) file exists is writable by the user under whose identity the script is running. If that's a problem, the script needs some configuration file indicating which directory is guaranteed to be writable by any user who may be running the script (and will use that directory to form the string f, the name of the counter file).

Note that I've kept the contents of the counter file in easily human-readable form -- that's for ease of debugging (and a tiny price to pay when one number is all that's in the file). It would of course be possible to keep the file in binary form instead.

If your script needs to persist many bits and pieces of info, a sqlite database file is probably the handiest way to keep them all together.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜