【问题标题】:What's a good automated way to change Python 2 code to code that is compatible with Python 2 and 3? [closed]将 Python 2 代码更改为与 Python 2 和 3 兼容的代码有什么好的自动化方法? [关闭]
【发布时间】:2018-01-08 16:36:52
【问题描述】:

我正在更改一些 Python 2 代码以与 Python 2 和 Python 3 兼容。翻译工具 2to3 可以很好地将 Python 2 代码转换为不一定与 Python 2 代码兼容的 Python 3 代码。一个例子是它如何将x.iteritems() 转换为x.items()。对于所有 Python 代码,我可能需要将 x.iteritems() 自动转换为 list(x.items()),等等。

如何做到这一点?

【问题讨论】:

  • "我可能需要将 x.iteritems() 自动转换为 list(x.items())" 嗯,但这并不等同......无论如何,你可能想检查一下出six
  • @juanpa.arrivillaga 是的,这就是重点。我需要将仅与 Python 2 兼容的代码自动更改为与 both Python 2 和 Python 3 兼容。2to3 工具似乎将代码转换为兼容 适用于 Python 3。
  • x.items() 怎么不兼容 Python 2?
  • @chepner 在 Python 2 中 x.items() 返回一个 (key, value) 对的列表,而在 Python 3 中 x.items() 是一个必须迭代的 itemview 对象,所以 list(x.items())需要替换 Python 2 中的 x.items()
  • 但是你的原始 Python 2 中没有 x.items();你有iteritems()。在 2 和 3 下运行时,您提议的更改会产生相同的语义,但仍会更改原始语义。如果不使用2to3没有一种方法可以同时保留 2 和 3 下的原始语义。

标签: python python-3.x python-2to3


【解决方案1】:

使用six 模块,它会为您提供您正在寻找的东西!完成转换后,您可以将 six 方法替换为原生 python 3。

【讨论】:

  • 嘿,谢谢。看起来这可能是一个解决方案。但是,我确实需要一个工具来将现有的 Python 2 代码转换为具有 six 模块的代码。我正在寻找一个自动化的解决方案。
  • 啊,我明白了。我不相信six 有相当于2to3。在这些情况下,尽管听起来很艰巨,但我确保一切都有单元测试,在 CI 期间将测试设置为在 python 2 和 3 上运行,然后在适当的地方开始插入 six
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2015-08-06
  • 1970-01-01
相关资源
最近更新 更多