简体   繁体   中英

How to generate UUID/GUID in Python 2.4 as UUID module is missing

Not able to find a way to generate UUID in Python 2.4 as the module was made available in Python 2.5 and is stable in 2.7. My machine is centos5 & due to other dependency cant really use or upgrade to Python 2.7

I did it with

#!/usr/bin/env python

import commands

def uuid():
        return commands.getstatusoutput('uuidgen')

if __name__ == "__main__":
        print uuid()[1]

It gives nice expected answer e79a890c-5e3a-4c3a-bfdb-5377389b69ac

The Linux Kernel has support to generate UUID. On my Debian system this functionality is accessible from the /proc pseudo-filesystem at /proc/sys/kernel/random/uuid :

>>> with open('/proc/sys/kernel/random/uuid') as f:
...     print(f.read())
... 
1e21ee4f-953e-4179-9bea-ac9a0b9189e7

If you are able to install libuuid you will have access to the uuidgen command line tool:

From man uuidgen

The uuidgen program creates (and prints) a new universally unique identifier (UUID) using the libuuid(3) library. The new UUID can reasonably be considered unique among all UUIDs created on the local system, and among UUIDs created on other systems in the past and in the future.

sh$ uuidgen 
c5f243c6-eb85-4eb9-a20e-97684d4baa1c

Use this: https://gist.github.com/mahmoudimus/56bcec09b69a2b5165aa

It's a python 2.3+ compatible version of the uuid module.

Example:

curl -O https://gist.githubusercontent.com/mahmoudimus/56bcec09b69a2b5165aa/raw/b1dd7633fff6ca0cc84a3b1fe435db7c65180dac/uuid.py

Use:

>>> import uuid
>>> uuid.__file__
'uuid.py'
>>> uuid.uuid1()
UUID('520a35d2-308f-11e4-b49f-600308a2f4f0')
>>> uuid.uuid1().hex
'53bcd6be308f11e4b49f600308a2f4f0'

You can also just use: https://pypi.python.org/pypi/pyuuid/0.0.1

pip install pyuuid

After bit of research, I found out that the best way to have UUID available in python 2.4 as the exact same as python 2.5+ is to download the UUID module from python source, as it's pure python code, so you can just include it under your project, for example:

wget http://svn.python.org/projects/python/trunk/Lib/uuid.py


Python 2.4.3 (#1, Jan  9 2013, 06:47:03) 
>>> import uuid
>>> print uuid.uuid1
<function uuid1 at 0x2b93db1f7758>
>>> print uuid.uuid1()
e95bdba8-652d-11e6-a87a-005056bf0031

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM