random 64-bit int

Paul Rubin phr-n2002b at NOSPAMnightsong.com
Thu Jul 25 04:50:28 EDT 2002


Jeff Davis <jdavis at empires.org> writes:
> It seems like the above works, but I'd like to know whether I am losing 
> randomness, or whether there is a more efficient or faster way to 
> accomplish that. Would it be a good idea to include a call to 
> random.seed()?
> 
> Also, it would be *really* nice if there was a good way to do that in 
> python2.1, which does not seem to allow the "q" type for unpack().

If you need really good randomness, for example for a security
application, don't use the random module at all.  Instead, if
you're using Linux or *BSD, read from the /dev/urandom device:

  randfile = open("/dev/urandom")

and then to get 8 bytes of randomness:

  bytes = randfile.read(8)

If you want to convert the bytes to a long int, the simplest way I
know is to convert to hex first:

  import binascii
  n = long(binascii.hexlify(bytes), 16)

If you're using Windows, the Cygwin package emulates /dev/urandom
using a Windows CAPI call (CryptGenRandom).  At the moment there's
no direct way to call that function in the standard Python distribution,
but I suppose you could write an extension.  Docs are at msdn.microsoft.com.



More information about the Python-list mailing list