ErnestoC
ErnestoC

Reputation: 2904

How can I generate a short and unique string based from input arguments?

I want to add file identifiers to a script I am creating that are short and unique. The identifier needs to be related to the input arguments given to the script from the CLI, so that the same identifier gets generated from the same arguments always.

I thought of hashing them with an MD5 hash that gets as input all the arguments provided by the user in the CLI:

import sys
import hashlib

file_id = hashlib.md5(str(sys.argv).encode("utf-8"))
print(file_id)

This only gives me an object description & memory location:

<md5 HASH object @ 0x0000324294...>

If I could get the actual hash I could extract the first 20 characters or so and it would be good enough for my use case.

Upvotes: 0

Views: 194

Answers (1)

Mohammad
Mohammad

Reputation: 3396

You can use the hexdigest method like so:

import sys
import hashlib

my_hash = hashlib.md5()
my_hash.update(str(sys.argv).encode("utf-8"))
print(my_hash.hexdigest())

Upvotes: 3

Related Questions