>>> from random import SystemRandom
>>> cryptogen = SystemRandom()
>>> [cryptogen.randrange(3) for i in range(20)] # random ints in range(3)
[2, 2, 2, 2, 1, 2, 1, 2, 1, 0, 0, 1, 1, 0, 0, 2, 0, 0, 0, 0]
>>> [cryptogen.random() for i in range(3)] # random floats in [0., 1.)
[0.2710009745425236, 0.016722063038868695, 0.8207742461236148]
Class that uses the os.urandom() function for generating random numbers from sources provided by the operating system. Not available on all systems. Does not rely on software state and sequences are not reproducible. Accordingly, the seed() and jumpahead() methods have no effect and are ignored. The getstate() and setstate() methods raise NotImplementedError if called.
Return a string of n random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom().
因为您希望在某个特定范围内生成整数,所以使用
random.SystemRandom
类要容易得多。创建该类的实例将为您提供一个对象,该对象支持random
模块的所有方法,但在封面下使用os.urandom()
。示例:等等,直接使用
urandom()
,你必须发明自己的算法,将它产生的随机字节转换成你想要的结果。别那么做;-)SystemRandom
替你做。注意文档的这一部分:
只需对^{} 返回的字节应用^{} 函数,就可以得到随机数列表,如下所示
引用
os.urandom
文档Python 3.6引入了一个新的secrets module,它“提供对操作系统提供的最安全的随机源的访问”。为了生成一些加密的安全号码,可以调用^{} 。
它将返回一个介于0和
n
之间的数字。相关问题 更多 >
编程相关推荐