无法在 python 3.5 上安装 'secrets'(pip,ubuntu 3.5)

Unable to install 'secrets' on python 3.5 (pip, ubuntu 3.5)

我正在尝试在 Python 3.5 和 Ubuntu 16.04 上使用库 secrets。它没有随 python 安装一起提供,我无法通过 pip 安装它。有没有办法让它在 python 3.5 上运行?

从 3.5 版开始,您尝试使用的模块不是 Python 的一部分。

看来那个版本的secrets也不能从pip下载

$ pip install secrets
Collecting secrets
 Could not find a version that satisfies the requirement secrets (from versions: ) No matching distribution found for secrets

在 Python 3.6 环境下工作时,可以立即导入该模块,因为它是标准库的一部分:

Python 3.6.3 (default, Mar  7 2018, 21:08:21)  [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> import secrets
>>> print(secrets)
<module 'secrets' from '/home/mikel/.pyenv/versions/3.6.3/lib/python3.6/secrets.py'>

没有用于此的 PyPi 模块并且 Ubuntu 使用古老的 python 版本这一事实非常烦人,如果有人能解决这个问题就太好了。与此同时:

要在旧版本 Python(>= 2.4 和 <= 3.5)中生成机密,您可以使用 urandom function from the os library.

示例:

from os import urandom

urandom(16) # same as token_bytes(16)
urandom(16).hex() # same as token_hex(16) (python >=3.5)

为了向后兼容并在支持时仍然使用新的秘密库,你可以做类似的事情

try:
    from secrets import token_hex
except ImportError:
    from os import urandom
    def token_hex(nbytes=None):
        return urandom(nbytes).hex()

如果你看一下 PEP 506, the proposal talks about how secrets is implemented and points to a Bitbucket repository 包本身的作者,它现在是官方 Python 标准库的一部分!

您可以使用名为 python2-secrets 的 Python 2.7、3.4 和 3.5 的秘密模块的反向移植。 (这个名字我觉得有点乱)

安装:

pip install --user python2-secrets

在 Python 3.x 中使用 pip install secret 代替