How to install a specific version of Python

Categories:

Prerequisites

  • Bash
  • git
  • C compiler
    • GCC
    • clang
  • make
  • nproc (coreutils)
  • checkinstall

Ubuntu

1sudo apt-get -y build-dep python3
2sudo apt-get -y install checkinstall git pkg-config

Script

 1install_python() {
 2  local -r repo_url='https://github.com/python/cpython.git'
 3  local -r repo_dir='/tmp/cpython'
 4  local args descr name email
 5
 6  args="$(getopt --options 'd:n:e:' --longoptions 'description:,name:,email:' -- "$@")"
 7  (( $? == 0 )) || return "$?"
 8  eval set -- "$args"
 9  while true; do
10    case $1 in
11      -d|--description) descr="$2"; shift ;;
12      -n|--name) name="$2"; shift ;;
13      -e|--email) email="$2"; shift ;;
14      --) shift; break ;;
15    esac
16    shift
17  done
18
19  local version="${1:?}"
20  local -a checkinstall_args=(
21    --strip
22    --pkgname="python${version%.*}"
23    --pkgversion="$version"
24    --provides="python-$version"
25  )
26  if [[ $name ]]; then
27    local maintainer="$name"
28    if [[ $email ]]; then
29      maintainer+=" \\<$email\\>"
30    fi
31    checkinstall_args+=(--maintainer="$maintainer")
32  fi
33
34  git clone --branch="v$version" --single-branch --depth=1 -- "$repo_url" "$repo_dir"
35  pushd "$repo_dir"
36  ./configure --prefix=/usr --enable-optimizations
37  make -s -j$(nproc) build_all
38  echo -e "${description:-Python $version}" > description-pak
39  sudo checkinstall "${checkinstall_args[@]}" make altinstall
40  popd
41  rm -rf "$repo_dir"
42}

Usage

1name="$(git config --get user.name)"
2email="$(git config --get user.email)"
3install_python --name="$name" --email="$email" 3.6.7