SoFunction
Updated on 2025-03-01

The correct way to use pip when multiple versions of python coexist

I want to learn Python3, but I cannot do without Python2 for the time being. How do you make them coexist on Windows?

At present, domestic websites often ask everyone to change one of them (well, I have also said this, so I will correct it here), so as to distinguish the names of the two executable files, but there is a major hidden danger in doing so, that is, the corresponding pip of the python that has modified the name will not be used.

What is the official solution?

In fact, the Python community gave an official solution to this problem a few years ago, but it has not been noticed in China.

When we installed Python3 (>=3.3), the Python installation package actually installed a launcher in the system, which is placed under the folder C:\Windows\ by default. This launcher allows us to specify whether to use Python2 or Python3 to run the code (of course, provided that you have successfully installed Python2 and Python3).

If you have a Python file called, then you can run it in Python2 like this

py -2

Similarly, if you want to run it in Python3, that's it

py -3

It is still quite troublesome to add parameters -2/-3 every time you run, so this launcher allows you to add instructions to the code to indicate whether the file should be interpreted and run by python2 or python3. The method of explanation is to add a line at the beginning of the code file

#! python2

or

#! python3

It means that the code file is interpreted and run using Python2 or Python3. In this way, your commands can be simplified to

py

Using pip

When Python2 and Python3 exist on Windows at the same time, their corresponding pips are called, so you cannot directly use the pip install command to install the software package. Instead, use the launcher to specify the version of pip. The command is as follows:

py -2 -m pip install XXXX

-2 still means using Python2, and -m pip means running the pip module, that is, running the pip command. If you are installing software for Python3, the command will be similar

py -3 -m pip install XXXX

#! Which one is written in front of python2 and #coding: utf-8?

There is another confusion for Python2 users. Python2 needs to add a line of instructions to the top of the code file before it can use Chinese in the code. If the Python version indicated that it is used also needs to add a line at the top of the file, which line should be placed in the first line?

#! Python2 needs to be placed in the first line, and the encoding instructions can be placed in the second line. So the beginning of the file should look like:

#! python2
# coding: utf-8

With these techniques, Python2 and Python3 can play happily together~

The above is the detailed content of the correct way to use pip when coexisting multiple versions of python. For more information about python pip, please pay attention to my other related articles!