gpt4 book ai didi

python - 如何在 Python 中生成可重现(带有种子)的随机 UUID

转载 作者:IT老高 更新时间:2023-10-28 22:15:42 25 4
gpt4 key购买 nike

Python的模块uuiduuid4()函数生成一个随机的UUID,而且好像每次都生成一个不同的:

In [1]: import uuid

In [2]: uuid.uuid4()
Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0')

In [3]: uuid.uuid4()
Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f')

我希望能够在每次运行脚本时生成相同的随机 UUID - 也就是说,我希望在 uuid4() 中播种随机生成器。有没有办法做到这一点? (或者通过其他方式实现)?

到目前为止我已经尝试过什么

我必须使用带有随机 128 位整数的 uuid.UUID() 方法生成 UUID(来自 random.Random() 的种子实例) 作为输入:

import uuid
import random

rd = random.Random()
rd.seed(0)
uuid.UUID(rd.getrandbits(128))

但是,UUID() 似乎不接受这个作为输入:

Traceback (most recent call last):
File "uuid_gen_seed.py", line 6, in <module>
uuid.UUID(rd.getrandbits(128))
File "/usr/lib/python2.7/uuid.py", line 133, in __init__
hex = hex.replace('urn:', '').replace('uuid:', '')
AttributeError: 'long' object has no attribute 'replace'

还有其他建议吗?

最佳答案

差不多了:

uuid.UUID(int=rd.getrandbits(128))

这是在 help 的帮助下确定的:

>>> help(uuid.UUID.__init__)
Help on method __init__ in module uuid:

__init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method
Create a UUID from either a string of 32 hexadecimal digits,
a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
in little-endian order as the 'bytes_le' argument, a tuple of six
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
the 'fields' argument, or a single 128-bit integer as the 'int'
argument. When a string of hex digits is given, curly braces,
hyphens, and a URN prefix are all optional. For example, these
expressions all yield the same UUID:

UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes='\x12\x34\x56\x78'*4)
UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)

Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
be given. The 'version' argument is optional; if given, the resulting
UUID will have its variant and version set according to RFC 4122,
overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.

关于python - 如何在 Python 中生成可重现(带有种子)的随机 UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41186818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com