Python多重处理无法与uuid.uuid4()很好地配合 [英] Python multiprocessing doesn't play nicely with uuid.uuid4()

查看:426
本文介绍了Python多重处理无法与uuid.uuid4()很好地配合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为文件名生成一个uuid,并且我还在使用多处理模块.不愉快的是,我所有的uuid都完全一样.这是一个小例子:

I'm trying to generate a uuid for a filename, and I'm also using the multiprocessing module. Unpleasantly, all of my uuids end up exactly the same. Here is a small example:

import multiprocessing
import uuid

def get_uuid( a ):
    ## Doesn't help to cycle through a bunch.
    #for i in xrange(10): uuid.uuid4()

    ## Doesn't help to reload the module.
    #reload( uuid )

    ## Doesn't help to load it at the last minute.
    ## (I simultaneously comment out the module-level import).
    #import uuid

    ## uuid1() does work, but it differs only in the first 8 characters and includes identifying information about the computer.
    #return uuid.uuid1()

    return uuid.uuid4()

def main():
    pool = multiprocessing.Pool( 20 )
    uuids = pool.map( get_uuid, range( 20 ) )
    for id in uuids: print id

if __name__ == '__main__': main()

我偷看了uuid.py的代码,似乎平台依赖某些OS级别的例程来保证随机性,因此我为python级别的解决方案而感到困惑(执行诸如重新加载uuid模块或选择新的随机种子).我可以使用uuid.uuid1(),但只有8位数字不同,我认为这完全是从时间派生的,这似乎很危险,特别是考虑到我正在执行 multiprocessing (因此代码可以在以下位置执行)完全相同的时间).关于这个问题有一些智慧吗?

I peeked into uuid.py's code, and it seems to depending-on-the-platform use some OS-level routines for randomness, so I'm stumped as to a python-level solution (to do something like reload the uuid module or choose a new random seed). I could use uuid.uuid1(), but only 8 digits differ and I think there are derived exclusively from the time, which seems dangerous especially given that I'm multiprocessing (so the code could be executing at exactly the same time). Is there some Wisdom out there about this issue?

推荐答案

如果需要这样做,这是生成自己的uuid4的正确方法:

This is the correct way to generate your own uuid4, if you need to do that:

import os, uuid
return uuid.UUID(bytes=os.urandom(16), version=4)

Python应该自动执行此操作-当本机_uuid_generate_random不存在时,此代码直接来自uuid.uuid4.您平台的_uuid_generate_random一定有问题.

Python should be doing this automatically--this code is right out of uuid.uuid4, when the native _uuid_generate_random doesn't exist. There must be something wrong with your platform's _uuid_generate_random.

如果您必须这样做,则不要自己解决它,而要让平台上的其他所有人遭受痛苦; 报告错误.

If you have to do this, don't just work around it yourself and let everyone else on your platform suffer; report the bug.

这篇关于Python多重处理无法与uuid.uuid4()很好地配合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆