Example of using 2to3 Conversion Tool in Python3, python32to3
There are many differences between python3 and python2, for example, in 2:
Copy codeThe Code is as follows:
Print "Hello, World! "
Raw_input ()
In 3, it becomes:
Copy codeThe Code is as follows:
Print ("Hello, World! ")
Input ()
Therefore, if the project developed by python2 needs to be migrated to 3, code conversion is required. Python3 comes with a conversion tool. The simplest example below is the 2to3 Conversion Tool.
Example: (2to3Test. py only contains the print line of code)
Copy codeThe Code is as follows:
# Python 2.7.6
# 2to3Test. py
Print "Hello, World! "
Python 27 can be compiled as follows:
Copy codeThe Code is as follows:
D: \ Python> python27 2to3Test. py
Hello, World!
I can't compile it with python33, Because print in 3 is a function, so there will be a syntax error.
Copy codeThe Code is as follows:
D: \ Python> python33 2to3Test. py
File "2to3Test. py", line 1
Print "Hello, World! "
^
SyntaxError: invalid syntax
The following uses the 2to3 tool in python3 for conversion:
Copy codeThe Code is as follows:
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
Finally, use python33 for compilation, and the result is displayed correctly.
Copy codeThe Code is as follows:
D: \ Python> python33 2to3Test. py
Hello, World!
Summary:
1. Directory. C: \ Python33 \ Tools \ Scripts \ 2to3. py. This tool exists in python2.6 and 2.7.
2. If the-w parameter is not added, the diff content corresponding to the conversion process is printed and output to the current window by default.
3. Added-w to write the modified content back to the original file.
4. If you do not want to generate a bak file, add-n. It is best to have bak.