将代码从 Python 2.x 转换为 3.x [英] convert code from Python 2.x to 3.x

查看:70
本文介绍了将代码从 Python 2.x 转换为 3.x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对我上一个问题的跟进,我正在使用 Senthil Kumaran 建议的 2to3 工具

This is a followup on my previous question, I am using the 2to3 tool as suggested by Senthil Kumaran

它似乎工作得很好,但它没有选择这部分:

It seems to work well but it doesn't pick up this part:

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 中应该是什么样子?

What should this look like in 3.2 ?

以下答案的变化很好,2to3 现在似乎可以正常工作了.然而,在 setup.py 构建中,我现在收到以下错误,请参阅我的新 问题.

the changes from the answer below are good, 2to3 now seems to work ok. Howevery in the setup.py build I now get the error below, see my new question.

推荐答案

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

Remove the comma after LexError. That works in both Python 2 and Python 3.

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

In Python 2 there was a rarely used syntax to raise exceptions like this:

raise ExceptionClass, "The message string"

这是这里使用的那个,但由于某种原因,可能是因为消息字符串周围有一个括号(根据 Senthils 测试,它是括号中的换行符),2to3 错过了更改为 much更好:

This is the one used here, but for some reason, maybe since there is a parenthesis around the message string (according to Senthils tests, it's the line break in the parenthesis that does it), 2to3 misses the change into the much better:

raise ExceptionClass("The message string")

所以它应该是这样的(在 Python 2 中)

So it should look like this (in 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 应该可以正常工作.

Because formatting that message on the same line as the raise is fugly. :-) Then in addition func_code has been renamed, so in Python 3 there are more changes. But with the above change 2to3 should work correctly.

这篇关于将代码从 Python 2.x 转换为 3.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆