1. Preface
Want to learn Python3, but temporarily without Python2. How do you make them coexist on Windows?
At present, the domestic website will often let you change one of the Python.exe name, so distinguish between two executable file name, but this has a major hidden danger, is modified the name of the python corresponding PIP will not be used.
In fact, the problem was that the Python community gave the official solution a few years ago, but it has not been noticed at home.
2. Run the Code
When we installed Python3 (>=3.3), the Python installation package actually installed a launcher Py.exe in the system, which was placed by default under Folder C:\Windows\. This initiator allows us to specify whether to run the code using PYTHON2 or Python3 (if you have successfully installed Python2 and Python3).
If you have a python file called hello.py, then you can run it with Python2.
py -2 hello.py
Similarly, if you want to run it with Python3, that's it.
py -3 hello.py
Adding parameter -2/-3 to each run is still a hassle, so py.exe this launcher allows you to add a description to the code to indicate whether the file should be run by python2 or interpreted by Python3. The way to do this is to add a line at the beginning of the code file
# !python2
Or
# !python3
Indicates that the code file is run with Python2 or Python3 interpretation, respectively. This way, your commands can be simplified when you run them to
py hello.py
3. Using PIP
When Python2 and Python3 are present on Windows, their corresponding Pip is called Pip.exe, so it is not possible to install the package directly using the PIP Install command. Instead, you use the initiator Py.exe to specify the version of the PIP. The command is as follows:
py -2 -m pip install XXXX
2 still means to run the PIP module using python2,-m pip, that is to run the PIP command.
If the software is installed for Python3, then the command resembles
py -3 -m pip install XXXX
4. Note
There is another confusion for Python2 users, Python2 to add a line of # Coding:utf-8 at the top of the code file to be able to use Chinese in the code. If you indicate that the Python version you are using also needs to add a line to the top of the file #! Python2, then, which one should be put in the first line?
The solution is to:
#! The python2 needs to be placed on the first line, and the coding instructions can be placed on the second line. So the beginning of the file should resemble:
# !python2# coding: utf-8
With these tips, Python2 and Python3 can play happily together.
Python3 and Python2 are installed under Windows, how can I differentiate between them?