我在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中的编码.
从 PyPI 安装包时,您必须使用项目的名称,该名称与您实际导入的顶级包的名称不同。一个明显的例子是pyserial和serial,它们的安装使用:
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,那么您将如何安装它们?