Python 3 os.urandom

2020-06-03 05:18发布

问题:

where can i find a complete tutorial or doc on os.urandom? i need to get get a random int to choose a char from a string of 80 char

im runing Ubuntu 12.04 on an aser aspire 5920

回答1:

If you just need a random integer, you can use random.randint(a, b) from the random module.

If you need it for crypto purposes, use random.SystemRandom().randint(a, b), which makes use of os.urandom().

Example

import random

r = random.SystemRandom()
s = "some string"
print(r.choice(s)) # print random character from the string
print(s[r.randrange(len(s))]) # same


回答2:

Might not exactly be on topic, but I want to help those coming here from a search engine. To convert os.urandom to an integer I'm using this:

 import os

 rand = int(os.urandom(4).encode('hex'), 16)
 # You can then 'cycle' it against the length.
 rand_char = chars_list[rand % 80] # or maybe '% len(chars_list)'

Note: The range of the index here is up to that of a 4-byte integer. If you want more, change the 4 to a greater value.

The idea was taken from here: https://pythonadventures.wordpress.com/2013/10/04/generate-a-192-bit-random-number/