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最好還是有。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
