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

时间:2011-03-31 08:20:03

标签: python python-3.x

这是我的previous question的后续内容,我正在使用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版本中,我现在收到以下错误,请参阅我的新question

3 个答案:

答案 0 :(得分:9)

函数的func_code属性已重命名为__code__,请尝试

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

作为代码段的第二行。

答案 1 :(得分:3)

删除LexError后的逗号。这适用于Python 2和Python 3。

在Python 2中,有一种很少使用的语法来引发这样的异常:

raise ExceptionClass, "The message string"

这是这里使用的那个,但由于某种原因,可能因为消息字符串周围有一个括号(根据Senthils测试,它是括号中的换行符),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应该可以正常工作。

答案 2 :(得分: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:])
相关问题