There are some differences between Python2 and Python3 in the syntax and use of modules (not explained in detail here). It is recommended that novices directly use python3 for code writing. In actual work, there are many operation and maintenance or test scripts that are still running continuously using python2. When we encounter batch work that needs to convert python3 into python2 (or convert python2 into python3), how should we deal with it? Do we need a line? How about manually modifying the code line by line? The answer is no. This article will introduce the specific implementation plan.
Python3.7 (comes with the conversion tool C: Python37Toolsscripts2to3) We can use it directly in the cmd command line:
python 2to3.py -w D:/test.py #Python2's test.py is converted to python3
The test.py file is very simple, just print the statement
print "hello.py"
C:Python37Toolsscripts>python 2to3.py -w D:/test.py RefactoringTool: Skipping optional fixer: buffer RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: set_literal RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored D:/test.py --- D:/test.py (original) +++ D:/test.py (refactored) @@ -1 +1 @@ -print "hello.py" +print("hello.py") RefactoringTool: Files that were modified: RefactoringTool: D:/test.py
After execution, check test.py, converted The code is as follows:
print("hello.py")
The -w parameter will overwrite the old file with the new file. Without -w, only the modified places will be displayed in the console window (and the content in the file will not be modified); the file will be Back up to .bak (for example, test.py.bak). If you do not need to generate a bak file, just add the parameter -n.
If you need to convert all the files in a certain folder, such as all the files in the test folder on drive D, enter in the command line:
python 2to3.py -w D:/test/
First install a Python package: lib3to2, pip install 3to2
After successful installation, a file called 3to2 will be generated in the directory C:Python37Scripts
for a certain python file that needs to be converted , for example, test.py in the root directory of drive D, enter in the command line:
python 3to2 -w D:/test.py #python3 test.py is converted to python2
if You need to convert all the files in a certain folder, such as all the files in the test folder on drive D, enter in the command line:
python 3to2 -w D:/test/
You can find the method of converting python 3 to python 2 and the method of converting python 2 to python 3 are extremely similar!
The above is the detailed content of Do you have a practical method to complete the conversion between Python3 and Python2 scripts in one second?. For more information, please follow other related articles on the PHP Chinese website!