Due to historical reasons, Python has two large version branches, Python2 and Python3. And because some libraries only support a certain version branch, Python2 and Python3 need to be installed on the computer at the same time. Therefore, how to use two versions of Python? Compatibility, how to make the script run on the corresponding Python version, this is worth summarizing.
For Ubuntu 16.04 LTS version, Python2 (2.7.12) and Python3 (3.5.2) are installed at the same time by default, and the default python version is 2.7.12.
Of course you can also use python2 to call it.
If you want to call python3, use python3.
Related recommendations: "Python Video Tutorial"
For Windows, it is a bit complicated. Because regardless of python2 or python3, the python executable file is called python.exe. The version number obtained by typing python in cmd depends on which version of the python path is higher in the environment variable. After all, Windows searches in order. For example, the order in the environment variable is like this:
Then the python version under cmd is 2.7.12.
On the contrary, it is the version number of python3.
This brings up a problem. If you want to use python2 to run a script, and later you want to use python3 to run another script, what do you do? Changing environment variables back and forth is obviously troublesome.
There are many methods on the Internet that are relatively simple and crude. Rename two python.exe, one to python2.exe and the other to python3.exe. This is certainly possible, but the method of modifying the executable file is not a good method after all.
I carefully searched some python technical documents and found another solution that I think is better.
Borrow a parameter of py to call different versions of Python. py -2 calls python2, py -3 calls python3
When the python script needs python2 to run, just before the script Add it and then run py xxx.py.
#! python2
When the python script needs python3 to run, just add, before the script, and then run py xxx.py.
#! python3
It’s that simple.
At the same time, this also perfectly solves the problem of pip reporting an error in an environment where python2 and python3 coexist, prompting Fatal error in launcher: Unable to create process using '"'.
When needed When using python2's pip, just
py -2 -m pip install xxx
When you need python3's pip, just
py -3 -m pip install xxx
The pip packages of python2 and python3 can be perfectly separated.
The above is the detailed content of Are python2.7 and 3.5 compatible?. For more information, please follow other related articles on the PHP Chinese website!