欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

CentOS 6.x系统升级Python到2.7版本的Shell脚本分享

程序员文章站 2022-06-20 20:14:08
在centos 6.x上,默认自带的python是2.6.x版本,这个版本的python有点老了,比如“collections.ordereddict”就是2.7才有的,而...

在centos 6.x上,默认自带的python是2.6.x版本,这个版本的python有点老了,比如“collections.ordereddict”就是2.7才有的,而且著名的python web框架django的新版(如:1.7)就不支持python2.6,最低要求是2.7了。而一些公司或者共有云上的服务器就是使用centos6.x,所以也就有了升级python到2.7的需求。

升级python之前,需要先安装一些工具和软件库,否则后面安装python或pip时可能出错。
python2.7通过源码安装,python可行执行程序默认是安装在/usr/local/bin/,一般来在$path中,/usr/local/bin是优先使用的(如果不是,需要自己设置一下path环境变量)。
在安装完python后,还需要安装easy_install和pip这两个最常用工具。

整个安装过程,我总结过如下一个shell脚本(以安装python2.7.8为例,以root权限运行),供参考:

复制代码 代码如下:

#!/bin/bash
# a script to install python 2.7 on centos 6.x system.
# centos 6.x has python 2.6 by default, while some software (e.g. django1.7)
# need python 2.7.
 
# install some necessary tools & libs
echo "install some necessary tools & libs"
yum groupinstall "development tools"
yum install openssl-devel zlib-devel ncurses-devel bzip2-devel readline-devel
yum install libtool-ltdl-devel sqlite-devel tk-devel tcl-devel
sleep 5
 
# download and install python
version='2.7.8'
python_url="https://www.python.org/ftp/python/$version/python-${version}.tgz"
 
# check current python version
echo "before installation, your python version is: $(python -v &2>1)"
python -v 2>&1 | grep "$version"
if [ $? -eq 0 ]; then
  echo "current version is the same as this installation."
  echo "quit as no need to install."
  exit 0
fi
 
echo "download/build/install your python"
cd /tmp
wget $python_url
tar -zxf python-${version}.tgz
cd python-${version}
./configure
make -j 4
make install
sleep 5
 
echo "check your installed python"
python -v 2>&1 | grep "$version"
if [ $? -ne 0 ]; then
  echo "python -v is not your installed version"
  /usr/local/bin/python -v 2>&1 | grep "$version"
  if [ $? -ne 0 ]; then
    echo "installation failed. use '/usr/local/bin/python -v' to have a check"
  fi
  exit 1
fi
sleep 5
 
# install setuptools
echo "install setuptools"
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py
# check easy_install version
easy_install --version
sleep 5
 
# install pip for the new python
echo "install pip for the new python"
easy_install pip
# check pip version
pip -v
 
echo "finished. well done!"
echo "if 'python -v' still shows the old version, you may need to re-login."
echo "and/or set /usr/local/bin in the front of your path environment variable."
echo "-------------------------"