看到一个博客:使用python内置2to3工具将python2代码转换为python3代码于是迫不及待的试了一下。
一个简单的例子(python2格式):
$ cat test2.py #存到test.py的代码,这里主要测试print用法,这几种print语法在2中都能正常输出,但是用3来解释的话,“print 123”就会报错
print 123
print (hello)
print(word)
按照博客教程,找到2to3的位置,我用的是mac,找的有点费劲(python3是我后来自己安装的,时间一长忘了位置,or run $ which 2to3):
/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/2to3
#测试
python /usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/2to3 -w test2.py
#-w参数使用,修改后的代码命名为test2.py,原来的代码命名为test2.py.bak保存下来
运行log如下:
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored test2.py
--- test2.py (original)
+++ test2.py (refactored)
@@ -1,3 +1,3 @@
-print 123
+print(123)
print (hello)
print(word)
RefactoringTool: Files that were modified:
RefactoringTool: test2.py
#不加-w,则不会产生新文件:
python /usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/2to3 test2.py
运行的log文件同上。
#博客说,-w -n效果是修改但不留备份文件,不建议使用。备份最好还是留一个吧!
ps:以后修改代码可以不用那么麻烦了!哦耶!!!
网友评论