【发布时间】:2012-12-14 15:59:54
【问题描述】:
下午好,这几天我尝试从运行在 Python3 下的 lincolnloop 获取 Python 二维码模块。它在 Python 2.x 上完美运行。 - https://github.com/lincolnloop/python-qrcode
总的来说,我对 Python 编程非常陌生,但我认为到目前为止我已经完成了我的功课。
第一个错误:
File "/usr/lib/python3.2/qrcode/util.py", line 274, in __init__
if not isinstance(data, basestring):
NameError: global name 'basestring' is not defined
因此,Python3 中不再存在 basestring,我使用此处找到的此代码语句来解决此问题。 - https://github.com/oxplot/fysom/issues/1
try:
unicode = unicode
except NameError:
# 'unicode' is undefined, must be Python 3
str = str
unicode = str
bytes = bytes
basestring = (str,bytes)
else:
# 'unicode' exists, must be Python 2
str = str
unicode = unicode
bytes = str
basestring = basestring
所以下一个错误出现了。
File "/usr/lib/python3.2/qrcode/util.py", line 285, in __init__
elif re.match('^[%s]*$' % re.escape(ALPHA_NUM), data):
File "/usr/lib/python3.2/re.py", line 153, in match
return _compile(pattern, flags).match(string)
TypeError: can't use a string pattern on a bytes-like object
所以我尝试在这里找到的解决方案 - Python TypeError on regex 并更改以下代码:
elif re.match('^[%s]*$' % re.escape(ALPHA_NUM), data):
到:
elif re.match(b'^[%s]*$' % re.escape(ALPHA_NUM), data):
以二进制模式处理正则表达式。但这会在同一行代码中引发下一个执行。
elif re.match(b'^[%s]*$' % re.escape(ALPHA_NUM), data):
TypeError: unsupported operand type(s) for %: 'bytes' and 'str'
我也尝试改变
ALPHA_NUM = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
到
ALPHA_NUM = b'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
但这不会改变 Execption。
所以这对我来说表明了与之前相同的错误,并且代码中的任何地方都必须是这种类型的错误,无论是字节还是字符串类型。但我找不到它。
我知道整个脚本对于深入研究 python 是非常复杂的,但是对于我的项目,我需要一个有效的 QR 码生成器。
谁能给我一个线索?提前致谢!
【问题讨论】:
-
最好的地方可能是从docs.python.org/2/library/2to3.html 开始 - 并修复无法自动翻译的错误
-
感谢您的回复。我研究了您今天早些时候提供的链接,但是自动 2to3 工具仅修复了我之前手动修复的“字符串,basestring”问题。 'TypeError: unsupported operand type(s) for %: bytes and str' 甚至没有出现。这就是我决定在 stackoverflow 上寻求帮助的原因。
-
你能换个方式把
data转换成字符串吗?你需要做data.decode(encoding)其中encoding是适当的编码(如'ascii')。抱歉,我没有浏览所有链接,所以也许这不是一个真正的解决方案。 -
Python 3 没有官方的
PIL版本(qrcode依赖于处理图像的依赖项)。没有测试(如果你不想让它对其他人有用;不要在没有测试的情况下移植)。
标签: python regex python-3.x typeerror