<p>从<a href="http://docs.python.org/library/random.html" rel="noreferrer">^{<cd1>} module documentation</a>:</p>
<blockquote>
<p>Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.</p>
</blockquote>
<p>从<a href="https://en.wikipedia.org/wiki/Mersenne_twister" rel="noreferrer">Wikipedia article on the Mersenne Twister</a>:</p>
<blockquote>
<p>It provides for fast generation of very high-quality pseudorandom numbers, having been designed specifically to rectify many of the flaws found in older algorithms.</p>
</blockquote>
<p>如果您有一个特定于操作系统的随机性源,可以通过<a href="http://docs.python.org/library/os.html#os.urandom" rel="noreferrer">^{<cd2>}</a>获得,那么您可以使用<a href="http://docs.python.org/library/random.html#random.SystemRandom" rel="noreferrer">^{<cd3>}</a>类代替。大多数<code>random</code>模块函数都可用作该类的方法。它可能更适合于加密目的,再次引用文档:</p>
<blockquote>
<p>The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.</p>
</blockquote>
<p>Python 3.6添加了一个<a href="https://docs.python.org/3.6/library/secrets.html" rel="noreferrer">^{<cd5>} module</a>和方便的方法来生成适合加密目的的随机数据:</p>
<blockquote>
<p>The <code>secrets</code> module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.</p>
<p>In particularly, <code>secrets</code> should be used in preference to the default pseudo-random number generator in the <code>random</code> module, which is designed for modelling and simulation, not security or cryptography.</p>
</blockquote>