[英]Python 2.x to 3.x - Append Syntaxerror: how to make it compatibale with Python 3.x from 2.x?
我有一个非常简单的问题,我很难追查 - 这意味着一个非常简单的答案。 在过去约 12 年左右的时间里,我在 python 2x 中编写了大量脚本,我不得不移植到 python 3x。
经过搜索和许多、许多、许多修复后,我遇到了一个难以追踪的更改。 我在如下所示的 e.append(lineno, line
) 中有语法错误。 关于如何改变它以使其与 python 3x 兼容的任何想法都将非常有用。
self.__options = {}
lineno = 0
e = None # None, or an exception
while 1:
line = fp.readline()
if not line:
break
lineno = lineno + 1
# skip blank lines
if string.strip(line) == '':
continue
# skip lines starting with '['
if line[0] == '[':
continue
# remove anything after '#'
line = string.split(line, '#')[0]
# key/value pairs can be seperated by whitespaces
for opt in string.split(line):
#if opt in string.whitespace:
# continue
keyval = string.split(opt, '=')
if len(keyval) == 2:
self.__options[keyval[0]] = keyval[1]
else:
e = ParsingError(fpname)
e.append(lineno, `line`)
# if any parsing errors occurred, raise an exception
if e:
raise e
这是非常简洁的历史语法。
对于反引号,我建议您参考以下答案: https://stackoverflow.com/a/1673087/2988730 。 要点是反引号是调用repr
的简写,直到它们在 python 3 中被删除。它们在文档中被称为“转换”操作:
代表(object
repr
返回包含 object 的可打印表示的字符串。 这与转换(反向引号)产生的值相同。 有时能够像普通的 function 一样访问此操作很有用...
append 本身是正常的,尽管没有记录使用ParsingError.append
方法:
def append(self, lineno, line):
从版本 3 开始, ConfigParser
已重命名为configparser
,但仍然具有ParsingError.append
方法。
因此,您需要进行一些更改:
在文件的开头,将from ConfigParser import ParsingError
更改为
从 configparser 导入 ParsingError
将有错误的行更改为
e.append(lineno, repr(line))
笔记
The multiple arguments to append
evoke, but aren't related to, a behavior of list.append
that hasn't been supported since python 2.0. 您可以在此处找到注释: https://docs.python.org/2/library/stdtypes.html#mutable-sequence-types 。 特别是脚注:
- Python 的 C 实现历来接受多个参数并将它们隐式连接到一个元组中; 这不再适用于 Python 2.0。 自 Python 1.4 起,已弃用此错误功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.