centos7安装特定版本的python

某个第三方库只支持某个特定版本的py,因此需要在同一个环境下安装不同版本的py

安装

  1. 当前环境:

    • centos7 + python2.6 —>目标:安装py2.7.6
  2. 从官网下载Pyhon https://www.python.org/download/releases/2.7.6

    • 选择下载Gzipped source tar ball (2.7.6) (sig)
  3. 安装本地编译环境

    1
    2
    yum groupinstall -y Development tools
    yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
  4. 解压并编译

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    tar -xvf Python-2.7.6.tgz

    cd Python-2.7.6

    ./configure --prefix=/usr/local/python2.7

    make

    make install

    安装完后的Python的可执行文件目录是 /usr/local/bin
    安装完后的python安装目录路径是 /usr/local/lib/python2.7
  5. 创建链接来使系统默认python变为python2.7

    1
    ln -fs /usr/local/python2.7/bin/python2.7 /usr/bin/python
  6. 查看当前的Python版本,确认已经是2.7.6

    1
    python –V
  7. 修改yum配置(若yum无法正常运行)

    1
    2
    3
    vi /usr/bin/yum

    将第一行的#!/usr/bin/python修改为系统原有的python版本地址#!/usr/bin/python2.6

问题

1. 安装 python3.7 时No module named _ssl

  1. 错误信息

    1
    2
    import _ssl       # if we can't import it, let the error propagate
    ImportError: No module named _ssl

    原因:openssl版本最低为1.0.2,但是centos 默认的为1.0.1,所以需要重新更新openssl

  2. 升级openssl

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # 安装依赖库
    yum install -y zlib zlib-dev openssl-devel sqlite-devel bzip2-devel libffi libffi-devel gcc gcc-c++

    wget http://www.openssl.org/source/openssl-1.1.1.tar.gz
    tar -zxvf openssl-1.1.1.tar.gz
    cd openssl-1.1.1
    ./config --prefix=$HOME/openssl shared zlib
    make && make install

  3. 设置环境变量LD_LIBRARY_PATH

    1
    2
    echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/openssl/lib" >> $HOME/.bash_profile
    source $HOME/.bash_profile
  4. 安装的时候指定刚才安装的openssl

    1
    2
    3
    4
    5
    6
    7
    8
    # 解压py安装包
    tar -zxvf Python-3.7.0.tgz

    # 进去解压后的目录,安装时指定刚才 openssl 的位置
    ./configure --prefix=$HOME/Py37 --with-openssl=$HOME/openssl
    make && make install
    echo $HOME

  5. 至此python3.7就安装完了,来检验下ssl模块能否被导入

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    [root@izbp12am8wqrn7t6wzgmydz Python-3.7.0]# echo $HOME
    /root
    [root@izbp12am8wqrn7t6wzgmydz Python-3.7.0]# cd /root/Py37/
    [root@izbp12am8wqrn7t6wzgmydz bin]# ./python3
    Python 3.7.0 (default, Sep 16 2018, 14:12:43)
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import ssl
    >>> import _ssl
    >>>