小编Aqu*_*ino的帖子

Python3和hmac.如何处理字符串不是二进制

我在Python2中有一个运行良好的脚本.

def _generate_signature(data):
   return hmac.new('key', data, hashlib.sha256).hexdigest()
Run Code Online (Sandbox Code Playgroud)

数据是输出的地方json.dumps.

现在,如果我尝试在Python 3中运行相同类型的代码,我会得到以下内容:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/hmac.py", line 144, in new
    return HMAC(key, msg, digestmod)
  File "/usr/lib/python3.4/hmac.py", line 42, in __init__
    raise TypeError("key: expected bytes or bytearray, but got %r" %type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'
Run Code Online (Sandbox Code Playgroud)

如果我尝试将密钥转换为字节,如下所示:

bytes('key')
Run Code Online (Sandbox Code Playgroud)

我明白了

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
Run Code Online (Sandbox Code Playgroud)

我仍然在努力理解Python 3中的编码.

python string encoding hmac python-3.x

36
推荐指数
3
解决办法
3万
查看次数

在 Python 中安装包时避免名称冲突

从 PyPI 安装包时,您必须使用项目的名称,该名称与您实际导入的顶级包的名称不同。一个明显的例子是pyserialserial,它们的安装使用:

pip install serial
pip install pyserial

Run Code Online (Sandbox Code Playgroud)

但两者都与以下内容一起使用:

pip install serial
pip install pyserial

Run Code Online (Sandbox Code Playgroud)

如果您浏览该site-packages文件夹,您会发现内容是两个软件包的组合,当然,这些文件会被要安装的​​最新软件包覆盖,从而产生不可预测的结果。

在Python中安装包时有没有办法避免这种名称冲突?假设您想同时使用 pyserial 和 serial,那么您将如何安装它们?

python pip package name-clash

5
推荐指数
0
解决办法
633
查看次数

标签 统计

python ×2

encoding ×1

hmac ×1

name-clash ×1

package ×1

pip ×1

python-3.x ×1

string ×1