As 2020 approaches, Python 2 is coming to an end. As of January 1, 2020, the Python core team will no longer provide any support for Python 2.

1. What to do?

Python3 is not forward compatible with Python2, so for those of you who have written Python2 and have a Python2 project running, it is time to migrate your project to Python3.

For those of you who are learning Python, don’t hesitate to go straight to the Python3 tutorial. If you are reading a tutorial written by Python2, throw it away.

2. Migration method

There are a number of automated tools that can help you migrate code from Python 2 to Python 3. For example, the built-in 2to3 module:

The basic call argument to 2to3 is a list of files or directories to convert. For directories, the Python source code is recursively searched.

Here is a source file for Python 2.x, example.py:

**def** greet(name):
    print "Hello, _{0}_!".format(name)
print "What's your name?"
name = raw_input()
greet(name)
Copy the code

Find your Python installation location, usually 2to3 will be in the Tools\scripts folder: C:\Python3X\Tools\scripts\2to3.py, enter the following command in CMD to convert Python2 code to Python3 code (since I am using Anaconda, the location may be different from yours) :

F:\Anaconda3\Scripts\2to3.exe example.py
Copy the code

It displays all changes with the following output:

RefactoringTool: Skipping optional fixer: buffer RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: set_literal RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored example.py -- example.py (original) +++ example.py (Refactored) @@ -1,5 +1,5 @@ def greet(name):print "Hello, {0}!".format(name)
-print "What's your name?"
-name = raw_input()
print("Hello, {0}!".format(name))
+print("What's your name?")
+name = input()
greet(name)
RefactoringTool: Files that need to be modified:
RefactoringTool: example.py 
Copy the code

If you want to write back to the file, remember to take the -w argument:

F:\Anaconda3\Scripts\2to3.exe -w example.py
Copy the code

Now it looks like this:

def greet(name):
    print("Hello, {0}!".format(name))
print("What's your name?")
name = input()
greet(name) 
Copy the code

Very convenient, one key to complete the modification. It can convert most Python2 code, and more detailed usage documentation is available here:

Docs.python.org/zh-cn/3.7/l…

However, 2to3.py is not a panacea. In some cases, you will have to manually convert the code.

So that’s the end of our article, if you enjoyed our Python tutorial today, please keep checking us out, and give us a thumbs up/check out below if it helped you


Python Dict.com Is more than a dictatorial model

The year 2020 has arrived, Python2 life has expired, please migrate