我正在围绕一个 dll 创建一个 python 包装器,并试图使其与 Python 2 和 3 兼容。dll 中的一些函数只接受字节并返回字节。这在 Py2 上很好,因为我可以只处理字符串,但在 Py3 上,我需要将 unicode 转换为字节以进行输入,然后将字节转换为 unicode 以进行输出。
例如:
import ctypes
from ctypes import util
path = util.find_library(lib)
dll = ctypes.windll.LoadLibrary(path)
def some_function(str_input):
#Will need to convert string to bytes in the case of Py3
bytes_output = dll.some_function(str_input)
return bytes_output # Want this to be str (bytes/unicode for py2/3)
确保兼容性的最佳方法是什么?仅使用 sys.version_info
并适本地编码/解码是否可以,或者在这种情况下确保版本之间兼容性的最可接受的方法是什么?
最佳答案
我通常会避免硬检查 Python 解释器版本。
您可能会发现此文档有帮助: http://python-future.org/compatible_idioms.html#strings-and-bytes
另请注意,您可以将此导入用于 unicode 文字:
from __future__ import unicode_literals
对于字节串:
# Python 2 and 3
s = b'This must be a byte-string'
至于将字符串转换为字节的最佳方法: https://stackoverflow.com/a/7585619/295246
在 Python 3 中将字符串转换为字节的推荐方法(从上面的链接中提取)如下:
>>> a = 'some words'
>>> b = a.encode('utf-8')
>>> print(b)
b'some words'
>>> c = b.decode('utf-8')
>>> print(c)
'some words'
>>> isinstance(b, bytes)
True
>>> isinstance(b, str)
False
>>> isinstance(c, str)
True
>>> isinstance(c, bytes)
False
你也可以做 bytes(a, 'utf-8')
,但是前面提到的方式更像 Pythonic(因为你可以用同样的方式从 bytes
回到 str
)。
关于python - 与 ctypes 一起使用的 dll 的字符串输入的 Py2/3 兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36723513/