I recently I needed to install python on a fresh Mac OS 11.5.2 install. I came across an article on freecodecamp explaining how to use pyenv so I’m trying it out. I’m also using virtual environments on top of pyenv. So far I’m only using one version of python so pyenv may not be useful to me. Here is what I’ve learned.
Pyenv
You can install pyenv with homebrew like this
brew install pyenv
I had to update my ~/.bash_profile with a couple of things,
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
if command -v pyenv 1>/dev/null 2>&1; then
eval "$(pyenv init --path)"
fi
Make sure the “–path” is there and not just a “-“. Apparently the “-” worked for older versions but now “–path” is needed.
Virtual Environments
In python 3 use this to create a virtual environment called “newvenv”:
python -m venv ~/.virtualenvs/newvenv
The virtual environment can go anywhere you want but ~/.virtualenvs is commonly used and is the default for virtualenvwrapper which I may setup later on.
Activate a virtual environment with
source ~/.virtualenvs/newenv/bin/activate
Deactivate a virtual environment with
deactivate
Once in a virtual environment, the command “python” will point to the interpreter for that environment. No need to give a full path or specific python version (ex: python3). Similarly the command “pip” points to the package installer for the active virtual environment.
Integrated Development Environment
For writing python code on my Mac in the past, I’ve used PyCharm (which is really good) Atom (which is fine), and Eclipse PyDev (which is not so good). I may go back to PyCharm in the future but I decided to try out Visual Studio Code this time since I already use it for other types of development.
Once python is installed on your computer you can create a python file in Visual Studio Code and it will prompt you to install the python extension.
Select An Interpreter
Visual Studio Code makes it easy to pick an interpreter. Just hit ⌘+Shift+P and get this menu:
Start typing “Python: Select Interpreter”. Hit Enter when that option pops up at the top of the list. Then you’ll see a list of interpreters to pick from, or an option to enter a custom path.
Editing, running, and debugging python code in Visual Studio Code have all been pretty intuitive so far.
Troubleshooting
Sometimes pip attempts to compile a package from source to get the newest version. If this is causing issues you can use “–only-binary=:all” to force it to use precompiled binaries.
pip install --only-binary=:all numpy