Python提供了2to3这个内置工具实现,更早的时候需要运行2to3.py这个文件并且传入待转换的文件地址,但是现在2to3已经成为了一个命令,可以在任意地方调用,格式为:
2to3 [参数] 文件地址
例如我创建一个py2test.py文件,用Python2的格式编写:
print 'hhh'
然后在该文件目录下打开命令行,输入
2to3 py2test.py
输出:
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored py2test.py
--- py2test.py (original)
+++ py2test.py (refactored)
@@ -1 +1 @@
-print 'hhh'
+print('hhh')
RefactoringTool: Files that need to be modified:
RefactoringTool: py2test.py
此时只会给出修改建议,不会修改py2test.py。如果要修改可以加上-w参数:
2to3 -w py2test.py
此时再打开py2test.py,发现已经转换为Python3的格式:
print('hhh')
2to3命令还非常贴心地在同目录下自动创建了py2test.py的备份文件py2test.py.bak,里面是转换之前的内容。