假设您有以下 Python2 代码:
#!/usr/bin/env python
import struct
struct.pack('s', 'hello')
这在 Python2 下工作正常,但它不会在 Python3 下运行,因为 struct.pack 的实现发生了变化。 struct.pack 现在需要一个字节对象作为字符串标识符,而不再是字符串。在 Python3 下运行此代码的修复类似于: struct.pack('s', bytes('hello', 'utf-8'))。但是同样,这段代码不会在 Python2 下运行:-)
我正在尝试编写独立于版本的代码,因为我不想强制任何人安装 python2 或 3。
让这段代码独立于版本的最佳方法是什么?
请您参考如下方法:
Python 2 str 类型基本上在 Python 3 中重命名为 bytes,而 unicode 类型变成了 str。您实质上是将 Python 2 中的字节串和 Python 3 中的 Unicode 字符串发送到 struct.pack()。
可能正确的解决方法是在 Python 2 和 3 中到处使用 Unicode(因此在使用 struct.pack() 时始终进行编码,无论 Python 版本如何)。
另一种方法是使用 isinstance 测试:
value = 'hello'
if not isinstance(value, bytes):
vaule = value.encode('utf8')
这在 Python 2 和 3 中都有效,因为在 Python 2 中 bytes 是 str 的别名。
