python3與python2的還是有諸多的不同,比如說在2中:
print "Hello,World!"
raw_input()
在3里面就成了:
print ("Hello,World!")
input()
所以如果用的python2開發的項目要遷移到3中,就需要進行代碼的轉換。Python3中自帶了個轉換工具,下面用個最簡單的例子來說說2to3轉換工具。
例子:(2to3Test.py 里面只有print這行代碼)
# python 2.7.6
# 2to3Test.py
print "Hello,World!"
用python27顯然是可以編譯的:
D:\Python>python27 2to3Test.py
Hello,World!
用python33就編譯不過了,因為3里print是函數,這樣寫就會有語法錯誤。
D:\Python>python33 2to3Test.py
File "2to3Test.py", line 1
print "Hello,World!"
^
SyntaxError: invalid syntax
下面用python3中自帶的2to3工具進行轉換:
D:\Python>python C:\Python33\Tools\Scripts\2to3.py -w 2to3Test.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored 2to3Test.py
--- 2to3Test.py (original)
+++ 2to3Test.py (refactored)
@@ -1 +1 @@
-print "Hello,World!"
+print("Hello,World!")
RefactoringTool: Files that were modified:
RefactoringTool: 2to3Test.py
最后用python33來進行編譯,結果顯示正確的。
D:\Python>python33 2to3Test.py
Hello,World!
總結:
1. 目錄. C:\Python33\Tools\Scripts\2to3.py. 其實在python2.6,2.7中都存在這個工具。
2. 如果不加-w參數,則默認只是把轉換過程所對應的diff內容打印輸出到當前窗口而已。
3. 加了-w,就是把改動內容,寫回到原先的文件了。
4. 不想要生成bak文件,再加上-n即可。 bak最好還是有。