You are getting 10 bytes. Python won't automatically turn them into numbers.
I recommend you grab the bytes in multiples of 4, then turn them into 32-bit unsigned integers, then scale them to whatever you need.
EDIT: the old code showed the idea but was poorly divided into functions. Here is the same basic idea but now conveniently packaged into functions.
import os
import struct
_random_source = open("/dev/random", "rb")
def random_bytes(len):
return _random_source.read(len)
def unpack_uint32(bytes):
tup = struct.unpack("I", bytes)
return tup[0]
UINT32_MAX = 0xffffffff
def randint(low, high):
"""
Return a random integer in the range [low, high], including
both endpoints.
"""
n = (high - low) + 1
assert n >= 1
scale_factor = n / float(UINT32_MAX + 1)
random_uint32 = unpack_uint32(random_bytes(4))
result = int(scale_factor * random_uint32) + low
return result
def randint_gen(low, high, count):
"""
Generator that yields random integers in the range [low, high],
including both endpoints.
"""
n = (high - low) + 1
assert n >= 1
scale_factor = n / float(UINT32_MAX + 1)
for _ in range(count):
random_uint32 = unpack_uint32(random_bytes(4))
result = int(scale_factor * random_uint32) + low
yield result
if __name__ == "__main__":
# roll 3 dice individually with randint()
result = [randint(1, 6) for _ in range(3)]
print(result)
# roll 3 dice more efficiently with randint_gen()
print(list(randint_gen(1, 6, 3)))
randommodule are "pseudo-random" - they're not truly random, they just do a good imitation./dev/randomdoes incorporate hardware entropy sources, at least on Linux. en.wikipedia.org/wiki//dev/random It uses network timings, measures times of keypresses, mouse movements, etc. If you have a CPU with a hardware random number instruction, it will use that. And if there isn't enough randomness to fulfill all requests, it will make callers wait while it collects more. The quality of entropy is much higher than a PRNG./dev/randomis a source of truly random bytes". Of course there are problems in certain conditions, but in the general case this is a much better random source than a PRNG. For best results, add additional hardware entropy sources as discussed here: security.stackexchange.com/questions/89/…/dev/randomimplementations unless I was generating keys to Fort Knox. I understand the point you made :). I am thinking of the distinction more from a physics standpoint, not a functional one.