Changing your default Python install: one tiny wrinkle that shouldn’t have tripped me up

Categories
HerpDerp Mucking About With Things Python Sysadminning

So you’ve installed a later and greater version of Python (Python 3.6.1 in my case) in /usr/local/bin and would like it to be used instead of your server’s default (and presumably older) python version when you type python at the shell prompt after logging in? The solution is widely documented.

  1. Add the following to the end of your .bash_profile, just before the export PATH line:
    PATH=/usr/local/bin:$PATH
  2. When you reload .bashrc or logout and login again, youll type python at the shell prompt and feel a twinge of annoyance at seeing you’ve been given the old Python install. At this point, if you’re (as clueless as) me, you’ll check to make sure that the the shell you’re using is indeed bash by typing echo $SHELL at the prompt. That returned /bin/bash in my case. If you are a bit wiser than I am, you’ll have first echoed the $PATH and seen that, yes, /usr/local/bin is being prepended.
  3. I’m sure you won’t do what I did, which was flail a bit, editing my .bash_profile and .bashrc files repeatedly and, somewhere along the line, introducing an error that led to many duplicate directory paths being added to $PATH, requiring me to find and run a code snippet to clean it up. The third solution from akostadinov’s answer to Remove duplicate $PATH entries with awk command on unix.stackexchange.com did the trick for me:
    PATH=`printf %s "$PATH" | awk -v RS=: '{ if (!arr[$0]++) {printf("%s%s",!ln++?"":":",$0)}}'`
  4. Here’s what you’ll probably do immediately after noticing that you aren’t getting your custom Python install. Realizing that bash is looking where you’ve told it to look but not finding anything named Python, you’ll cd into /usr/local/bin and have a look around. The Python executable in /usr/local/bin is named Python[MajorVersion].[MinorVersion] (Python3.6 for me). There may be a symlink to it named Python[MajorVersion] (e.g. Python3) but to make the command python call your custom Python, you’ll need to create another symlink:
    ln -s python3.6 python

Shazaam! Fixed.