當前安裝的為Centos7。2,Basic Web Server版本,默認安裝的python版本為2.7.5
[root@localhost Python-3.5.0]# python Python 2.7.5 (default, Jun 20 2019, 20:27:34) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>>
查看python可執行文件,另外結合使用whereis pip發現未安裝pip
安裝python3
安裝yum-utils
yum -y install yum-utils
安裝gcc
yum -y install gcc
下載python3(如果需要下載其他版本,可以修改下面的版本號嘗試下載)
wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tgz
3.7.3版本安裝需先安裝依賴
yum -y install libffi-devel tk-devel readline-devel openssl-devel zlib
解壓
tar -zxvf Python-3.7.3.tgz
進入目錄
cd Python-3.7.3/
配置,編譯和安裝
./configure prefix=/usr/python3 && make && make install
添加軟連接
python3安裝結束后,需要將python3和pip3軟連接到/usr/bin下,使其不用輸入全路徑也可以使用
ln -s /usr/python3/bin/pip3 /usr/bin/pip3 ln -s /usr/python3/bin/python3 /usr/bin/python3
執行python3檢測是否安裝成功
[root@localhost Python-3.7.3]# python3 Python 3.7.3 (default, Jun 27 2019, 09:55:36) [GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
安裝requests檢測pip是否安裝成功,並寫個簡單腳本測試數據抓取
pip3 install requests
#!/usr/bin/python3 import requests r=requests.get("http://www.baidu.com") r.encoding='utf-8' print(r.text)
卸載上述編譯的3.7.3版本時,只需要刪除編譯安裝目錄即可。
設置環境變量
當安裝了第三方模塊,如requests時,Python從如下位置查找requests
1、當前目錄
2、如果當前目錄不存在,則Python將搜索變量PYTHONPATH下的每個目錄
3、如果以上都找不到,Python會去默認路徑下查找,linux下,默認路徑一般為/usr/local/lib/python/
PS:
1、整個過程不需要卸載之前的2.7.5,若一定要卸載,則有些軟件也需要重裝,比如yum等。
2、如果安裝后刪除后者操作方向鍵等出現以下現象,則可能是 readline-devel沒有安裝或者沒有安裝成功,重新安裝依賴,並重新編譯安裝python3.7.3
[root@localhost Python-3.7.3]# python3 Python 3.7.3 (default, Jun 27 2019, 09:55:36) [GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print ()^[[D^[[D^[[D