Skip to content

Instantly share code, notes, and snippets.

@Ogaday
Last active August 18, 2023 13:55
Show Gist options
  • Select an option

  • Save Ogaday/53d84080b89fc8362103069c5a5e73ff to your computer and use it in GitHub Desktop.

Select an option

Save Ogaday/53d84080b89fc8362103069c5a5e73ff to your computer and use it in GitHub Desktop.
Installing Python From Source
#!/bin/bash
function log_error() {
msg=$1
echo $msg >&2
}
function install() {
set -e
VERSION=${1:-$PYTHON_VERSION}
MD5SUM=${2:-$PYTHON_MD5SUM}
TARFILE="https://www.python.org/ftp/python/${VERSION}/Python-${VERSION}.tgz"
DIRECTORY="Python-${VERSION}"
if [ -z $VERSION ]
then
log_error "\$PYTHON_VERSION not set."
return 1
fi
if [ -z $MD5SUM ]
then
log_error "\$PYTHON_MD5SUM not set."
return 1
fi
wget \
--no-clobber \
--quiet \
-P /tmp/ \
$TARFILE
HASH=$(md5sum /tmp/Python-${VERSION}.tgz | cut -d " " -f 1 -)
if [ $MD5SUM != $HASH ]
then
log_error "md5sum '${HASH}' doesn't match expected md5sum '${MD5SUM}'"
fi
tar -C /tmp/ -xzf "/tmp/${DIRECTORY}.tgz"
cd "/tmp/${DIRECTORY}"
./configure --enable-optimizations --with-lto --prefix=$HOME/.local/
make
make test
make altinstall
}
install $@
exit

Installing Python From Source

Installing Python on Linux isn't so hard. These are my notes for installing on Ubuntu.

  1. Install build dependencies using apt.
  2. Choose and download the version of Python you'd like to install from the releases page.
  3. Extract the directory
  4. Run ./configure and make to install

You will need some dependencies, listed in the development guide.

There are some configuration options. We install to .local for a user install of Python, and use make altinstall to install alongside any existing Python installations.

Steps

Example steps:

sudo apt-get install build-essential gdb lcov pkg-config \
      libbz2-dev libffi-dev libgdbm-dev libgdbm-compat-dev liblzma-dev \
      libncurses5-dev libreadline6-dev libsqlite3-dev libssl-dev \
      lzma lzma-dev tk-dev uuid-dev zlib1g-dev
export VERSION=3.9.5
curl "https://www.python.org/ftp/python/${VERSION}/Python-${VERSION}.tgz" | tar -xzf -
cd ${VERSION}
./configure --prefix=$HOME/.local/ --enable-optimizations --with-lto
make
make test
make altinstall

Script

I've also made a script that automates some of the above steps.

Usage:

./install_py.sh 3.10.11 7e25e2f158b1259e271a45a249cb24bb
# OR
PYTHON_VERSION=3.10.11 PYTHON_MD5SUM=7e25e2f158b1259e271a45a249cb24bb ./install_py.sh

Troubleshooting

After make, you might see some modules can't be found. In that case, you may need to install the dependencies via apt or from source. (OpenSSL especially)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment