There is a lot of confusing information about virtual environments in python out there, in part because the tool chain has evolved over many years.
I decided to follow the advice of Real python and The hitchhiker's guide to python and manage both multiple python versions and multiple virtual environments with pyenv
I used homebrew to install pyenv on my linux machine running MX 23.1 Libretto.
brew update
brew install pyenvAfterwards, I executed the following code to add three
lines to my ~/.bashrc file, as recommended
on the pyenv README page.
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrcNext, I used pyenv to install the latest release version
of python, version 3.12.1 (at the time of writing).
I ran into the issue reported here,
preventing me from installing python with pyenv
(see below). It turns out that brew masks the system's
pkg-config, intefering with the compilation of python.
I unlinked pkg-config with the following command, and
the installation succeeded:
brew unlink pkg-configFirst, I listed the (many) python versions pynev is
aware of:
pyenv install --listand then installed the version of my choice:
pyenv install -v 3.12.1Finally, I set my new python installation as the default version:
pyenv global 3.12.1To make using virtual environments with pyenv easier,
I installed the pyenv-virtualenv plugin:
brew install pyenv-virtualenvThe pyenv virtualenv command creates a new virtual
environment for the specified python version (e.g. 3.12.1).
pyenv virtualenv 3.12.1 rangoAll virtual environments created in this way are stored in
the same location, by default the ~/.pyenv/versions folder:
ls ~/.pyenv/versions/The following command activates my new rango virtual environment:
pyenv activate rango
python --version # 3.12.1and the equivalent command deactivates it:
pyenv deactivate rangoTo use my virtual environment in the VS Code IDE:
- Open VSCode preferences (Ctrl + ,)
- Search for
venv. - Add ~/.pyenv to the “Venv Path” text box.
Afterward, I can choose the python interpretor from the rango
virtual environment (once I have created a python file) by
clicking on the python version in the bottom right of the vscode
window.