-3

What is the best way to create a python script by calling which, it will ALWAYS generate a new UNIQUE ID (Auto-incremental)?

You run the script and it will tell you 1, then close script and open again and will tell you 2.

Purpose of it is to create a script which will be used across and this ID will be used to track the latest changes and so on.

P.S. I'm not talking to make a function which will do it.

Mahdi
  • 3,188
  • 2
  • 20
  • 33
J.Doe
  • 111
  • 1
  • 2
  • 12
  • Have you tried anything yourself? – Jan Jan 14 '19 at 15:08
  • 1
    If you want to run this script as a standalone tool, it has a different answer depending on the operating system you are using. If you are planning on having a database running along with your script, you could use the database facilities (for example, using a `SEQUENCE` and `nextval` in PostgreSQL). If you have a consensus platform such as zookeeper, you could use Zookeeper and Curator to generate it. – PEdroArthur Jan 14 '19 at 15:16
  • Take a look at the [`uuid`](https://docs.python.org/3/library/uuid.html) module. – alexis Jan 14 '19 at 15:17
  • @Kevin SOrry if it looks like this, to write a code with auto incremental this is easy enough .... My question is regarding how to store this value. For example, I create python script and write the function which will autoincrement value, BUT after I will close it record lost. So I need some sort of single point which all other python scrits will be using. I can see currently only in the way to create for example text file which will store value and each time update this value in text. BUT I believe there is a proper way to do it. – J.Doe Jan 14 '19 at 15:19
  • @Kevin - P.S. I can write script my self, I just need the theory behind, what method to use. – J.Doe Jan 14 '19 at 15:19
  • Depending on expected frequency of use, it might be sufficient and simplest to return number of seconds since some time point. – Aaron Hayman Jan 14 '19 at 15:20
  • @alexis Nope, this is have to be autoincremental UID which will be used by different python scripts. – J.Doe Jan 14 '19 at 15:20
  • @AaronHayman Please read this ^ – J.Doe Jan 14 '19 at 15:20
  • If you're asking "how can I store data in between executions of my program?", the simplest possible solution is: write the data to a file. Are you familiar with the open() function? – Kevin Jan 14 '19 at 15:21
  • Simple solution: Write a byte to a file every time your UID program is run. Use the file size as the unique Id. ;-) If you won't be running dozens of instances concurrently or generating billions of IDs, you'll be fine. If you will be, use a database. – alexis Jan 14 '19 at 15:45
  • There is a danger with reading and writing directly to a single file with several scripts that file gets used concurrently. If this is likely to be a problem, you will need to make a server that is in charge of maintaining the count file and dispensing IDs, then all other scripts become clients that make requests to the server. – Aaron Hayman Jan 14 '19 at 15:55

5 Answers5

3
import uuid

uniqueid = uuid.uuid1()
momaji
  • 161
  • 1
  • 6
0

I assume you have a script, it will generate some result every time it is executed. Then you need need a value that (1) distinguish one result from another and (2) shows which result came last. Is that right? If so, we have many options here. In the simplest case (a script always running in the same machine) I would suggest two options

Save a count to a file

In this case, you would have a file and would read the number from it:

try:
    with open('count.txt') as count_file:
        content = count_file.read()
        count = int(content)
except Exception:
    count = 0

After doing whatever your script does, you would write to the file the value you've read, but incremented:

with open('count.txt', 'w') as count_file:
    count_file.write(str(count + 1))

Save the timestamp

A simpler option, however, is not to increment a value but get a timestamp. You could use time.time(), that returns the number of seconds since Unix epoch:

>>> import time
>>> time.time()
1547479233.9383247

You will always know which result came later than the others. Personally, however, I would rather format the current time, it is easier to read and reason about:

>>> from datetime import datetime
>>> datetime.now().strftime('%Y%m%d%H%M%S')
'20190114132407'

Those are basic ideas, you may need to pay attention to corner cases and possible failures (especially with the file-based solution). That said, I guess those are quite viable first steps.

A technical note

What you want here is to a program to remember a piece of information between two or more executions, and we have a technical term for that: the information should be persistent. Since you asked for an autoincrementing feature, you wanted a persistent count. I suspect, however, you do not need that if you use the timestamp option. It is up to you to decide what to do here.

brandizzi
  • 26,083
  • 8
  • 103
  • 158
  • The first part of your explanation if what I'm looking, This is was of the ideas, as I mentioned in comments (extremely sorry for bad explanation). What do you think about "Is it the best option?" how about concurrency? may be better to write to mini database? I need at the end the only piece of code which will generate unique ID and keep track of it, and multiple scripts can use it, but I think simply write it to the file is not the best option – J.Doe Jan 15 '19 at 05:38
0

Since you didnt provide any code, I will also not provide any code.

Solution 1: Unique ID

1) TIME: create function to give you timestamp

2) ID: create function that generate long string with random numbers and letters

  • This is of course 'risky' because there is a chance you will generate already existing ID, but from statistical point of view, it is so called 'impossible even if it is possible'

save in file or somewhere

Solution 2: offset - incremental

1) have file with a 0 in it.

2) open a file, read line, convert to integer, increment to +1, write in a file.

Note:

Your title is wrong. One moment you talk about UNIQUE ID, Next moment you are talking about offset. Unique ID and counting running python script are quite contradicting ideas

Martin
  • 3,333
  • 2
  • 18
  • 39
  • I need a single point which by calling always generate new autoincrement ID. This is will allow to keep track of changes and so on. – J.Doe Jan 15 '19 at 05:44
0

I had the same situation. I ended up in creating a CSV file so that I can map variable names.

def itemId_generator(itemIdLocation):
    # Importing value of ItemID from the csv file
    df = pd.read_csv(itemIdLocation)

    #return value which is current ItemID in the csv file
    ItemId = df.loc[0, 'ItemId']

    # If loop to set limit to maximum Item ID
    if ItemId>= 10000:
        df.loc[0, 'ItemId'] = 1

    elif ItemId<10000:
        # updating the column value/data
        df.loc[0, 'ItemId'] = df.loc[0,'ItemId'] + 1
    else:
        print("Invalid value returned")
        sys.exit()

    # writing new ItemID into the file
    df.to_csv(itemIdLocation, index=False)

    # The function .item() converts numpy integer to a normal int
    return str(ItemId.item())
pythoner
  • 21
  • 4
-1

If there is any chance of the file being accessed concurrently, it is best to lock the file. Keep trying if the file is locked.

http://tilde.town/~cristo/file-locking-in-python.html

Old answer: You could store it as an environment variable on the system. If not set, initialise to 1. Else increment it by 1.

riddler
  • 467
  • 3
  • 13
  • Um, a process cannot modify the environment of its caller. And what about restarts? Please give a bit of code (or other specifics) to explain what you are thinking. – alexis Jan 14 '19 at 15:15