【问题标题】:convert code from Python 2.x to 3.x将代码从 Python 2.x 转换为 3.x
【发布时间】:2023-03-20 01:19:01
【问题描述】:

这是我 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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

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

    作为代码 sn-p 的第二行。

    【讨论】:

      【解决方案2】:

      删除 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)
      

      因为在与 raise 相同的行上格式化该消息是很丑陋的。 :-) 然后另外 func_code 已被重命名,因此在 Python 3 中有更多的变化。但是通过上述更改,2to3 应该可以正常工作。

      【讨论】:

      • 建议的更改没问题,2to3 现在可以接受它,但我在构建中遇到错误(在 2to3 更改之后)。我编辑了我的问题。
      • @Remko:这是一个不同的问题。您应该删除编辑并提出一个新问题。除了新问题是重复的。 :) stackoverflow.com/…
      • 创建了新问题,如果重复,请指出我,因为我发现了几个具有相同错误但无法从他们那里得到解决方案的问题。
      • 接受这个答案,因为它是最完整的
      【解决方案3】:

      你遇到了什么问题? 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:])
      

      【讨论】:

      • 哦,我明白了。很可能是 2to3 的错误。
      • 是的,用 2to3 覆盖所有奇怪的情况可能会很痛苦。
      • 是的,它似乎是换行符
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多