Linux学习笔记:安装python

时间:2022-06-30 15:11:53

一般linux自带python2,如果需要python3以上版本,可以不需要卸载自带的python2,二者可以共存。只需要配置相应的环境变量即可。

具体回答可以参考这篇文章 https://*.com/questions/26282986/how-to-update-python-2-7-to-python-3-in-linux

其内容是:

Python 2 and 3 can safely be installed together. They install most of their files in different locations. So if the prefix is /usr/local, you'll find the library files in /usr/local/lib/pythonX.Y/ where X.Y are the major and minor version numbers.
The only point of contention is generally is the file python itself, which is generally a symbolic link.
Currently it seems most operating systems still use Python 2 as the default, which means that python is a symbolic link to python2. This is also recommended in the Python documentation.
It is best to leave it like that for now. Some programs in your distributions may depend on this, and might not work with Python 3.
So install Python 3 (3.5.1 is the latest version at this time) using your favorite package manager or compiling it yourself. And then use it by starting python3 or by putting #!/usr/bin/env python3 as the first line in your Python 3 scripts and making them executable (chmod +x <file>)

上面内容的大意是:python2和3可以共存,可以安装在不同的位置。例如 /usr/local/lib/pythonX.Y,这X.Y代表了主要版本。而需要配置全局环境变量其实就是python这个文件自身,它可以是一个快捷方式。同时建议不要随意修改系统内置的python版本。(之前我在centos7上面修改了python版本,导致yum命令使用出错)

如果需要执行依赖python3的python脚本,只需要要在文件第一行加上 #!/usr/bin/env python3 ,或者加上#!/usr/bin/python3。二者的区别可以见这篇文章 https://www.jianshu.com/p/400c612381dd

如果提示 /usr/bin/python^M: bad interpreter: No such file or directory,这是因为windows和linux行尾标识符不同,可以用文本编辑工具File - Conversions - DOS - UNIX,或者 Edit - EOL Conversion -UNIX(LF)。

如何安装python3版本:

yum install epel-release

yum install python36

上面的python36是仓库中的最新版本,后面可能会更新到37等更高的版本。

如果依赖python3的脚本,同时依赖其他模块,此时用pip install package就会出现问题,因为这个pip命令其实是去执行系统内置的python2中的pip,如果模块不兼容python2就会报错。

在这个问题用有解答 https://*.com/questions/50408941/recommended-way-to-install-pip3-on-centos7

解决办法是安装pip3,这个pip3是python3的包管理器,如果使用pip3 install package,就可以安装相应的模块到python3环境下。

安装pip3步骤(接着上面python36安装完成后):

yum install python36-devel
yum install python36-setuptools
easy_install-3.6 pip

然后查看pip3的版本

pip3 --version

尽量不要删除和修改linux内置的python版本。python2和python3是可以共存的。