将代码从Python 2.x转换为3.x

1 投票
3 回答
4160 浏览
提问于 2025-04-16 14:47

这是我之前提到的一个问题的后续内容,链接在这里:之前的问题。我正在使用Senthil Kumaran建议的2to3工具。

这个工具似乎运行得不错,但它没有处理这一部分:

raise LexError,("%s:%d: Rule '%s' returned an unknown token type '%s'" % (
    func.func_code.co_filename, func.func_code.co_firstlineno,
    func.__name__, newtok.type),lexdata[lexpos:])

在3.2版本中,这部分应该是什么样子的呢?

编辑:下面回答中的修改很好,现在2to3工具似乎可以正常工作了。不过在setup.py构建时,我现在遇到了下面的错误,详细情况请看我新的问题

3 个回答

1

你遇到了什么问题?2to3工具似乎可以很好地帮我转换这个。

-    raise LexError,("%s:%d: Rule '%s' returned an unknown token type '%s'" % (func.func_code.co_filename,func.func_code.co_firstlineno,func.__name__,newtok.type),lexdata[lexpos:])
+    raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % (func.__code__.co_filename,func.__code__.co_firstlineno,func.__name__,newtok.type),lexdata[lexpos:])
11

函数的 func_code 属性已经改名为 __code__,所以你可以试试

func.__code__.co_filename, func.__code__.co_firstlineno,

作为你代码片段的第二行。

3

把LexError后面的逗号去掉,这样在Python 2和Python 3中都能正常工作。

在Python 2中,有一种很少用到的语法可以用来抛出异常,像这样:

raise ExceptionClass, "The message string"

这里用的就是这种语法,但不知道为什么,可能是因为消息字符串周围有括号(根据Senthil的测试,是括号里的换行符导致的),所以2to3工具没有把它改成更好的:

raise ExceptionClass("The message string")

所以在Python 2中,它应该看起来像这样:

message = "%s:%d: Rule '%s' returned an unknown token type '%s'" % (
           func.func_code.co_filename, func.func_code.co_firstlineno,
           func.__name__, newtok.type),lexdata[lexpos:])
raise LexError(message)

因为把消息格式化在和抛出异常同一行上看起来很糟糕。:-) 另外,func_code这个名字也改了,所以在Python 3中还有更多的变化。不过只要做了上面的改动,2to3工具就应该能正常工作了。

撰写回答