python3與python2的還是有諸多的不同,比如說(shuō)在2中:
print "Hello,World!"
raw_input()
在3里面就成了:
print ("Hello,World!")
input()
所以如果用的python2開(kāi)發(fā)的項(xiàng)目要遷移到3中,就需要進(jìn)行代碼的轉(zhuǎn)換。Python3中自帶了個(gè)轉(zhuǎn)換工具,下面用個(gè)最簡(jiǎn)單的例子來(lái)說(shuō)說(shuō)2to3轉(zhuǎn)換工具。
例子:(2to3Test.py 里面只有print這行代碼)
# python 2.7.6
# 2to3Test.py
print "Hello,World!"
用python27顯然是可以編譯的:
D:\Python>python27 2to3Test.py
Hello,World!
用python33就編譯不過(guò)了,因?yàn)?里print是函數(shù),這樣寫就會(huì)有語(yǔ)法錯(cuò)誤。
D:\Python>python33 2to3Test.py
File "2to3Test.py", line 1
print "Hello,World!"
^
SyntaxError: invalid syntax
下面用python3中自帶的2to3工具進(jìn)行轉(zhuǎn)換:
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來(lái)進(jìn)行編譯,結(jié)果顯示正確的。
D:\Python>python33 2to3Test.py
Hello,World!
總結(jié):
1. 目錄. C:\Python33\Tools\Scripts\2to3.py. 其實(shí)在python2.6,2.7中都存在這個(gè)工具。
2. 如果不加-w參數(shù),則默認(rèn)只是把轉(zhuǎn)換過(guò)程所對(duì)應(yīng)的diff內(nèi)容打印輸出到當(dāng)前窗口而已。
3. 加了-w,就是把改動(dòng)內(nèi)容,寫回到原先的文件了。
4. 不想要生成bak文件,再加上-n即可。 bak最好還是有。