【发布时间】:2018-08-19 11:29:57
【问题描述】:
我正在尝试在 Ubuntu 16.04 上的 Python 3.5 上使用库 secrets。它不附带 python 安装,我无法通过 pip 安装它。有没有办法让它在 python 3.5 上工作?
【问题讨论】:
-
您在尝试使用 pip 安装时看到哪些错误?
标签: python python-3.x cryptography python-3.5
我正在尝试在 Ubuntu 16.04 上的 Python 3.5 上使用库 secrets。它不附带 python 安装,我无法通过 pip 安装它。有没有办法让它在 python 3.5 上工作?
【问题讨论】:
标签: python python-3.x cryptography python-3.5
没有 PyPi 模块并且 Ubuntu 使用古老的 python 版本这一事实非常烦人,如果有人能解决这个问题就好了。同时:
要在旧版本的 Python(>= 2.4 和 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()
【讨论】:
urandom()在请求的字节数为None时没有相同的“合理默认”规则。因此,您的向后兼容解决方案需要手动将 nbytes 设置为某个“合理的默认值”(尽管我不确定有多少人使用此功能)。
您可以通过 python2-secrets 的名称使用 Python 2.7、3.4 和 3.5 的秘密模块的反向移植。 (这个名字在我看来有点混乱)
安装:
pip install --user python2-secrets
【讨论】:
您尝试使用的模块不是 Python 3.5 版的一部分。
在那个版本中似乎也无法从 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'>
【讨论】:
在 Python 3.x 中,请改用 pip install secret
【讨论】:
如果你看一下PEP 506,该提案谈到了secrets 是如何实现的,并指向包本身的作者的Bitbucket repository,它现在是官方Python 标准库的一部分!
【讨论】: