How to install a virtual Python environment

You probably don't want to mess with your system Python environment as that can lead to system instability. You probably do want to use multiple versions of Python if you are developing in Python. This note is a very quick note on getting a virtual instance of Python up and running using the venerable Pyenv now on their 90th release.

I have used Pyenv to manage my Python installs on FreeBSD since FreeBSD 12 and with great success. Without further ado, here's your 3 minute guide to virtual Python in FreeBSD.

1. Get Pyenv

Code:
git clone https://github.com/pyenv/pyenv.git ~/.pyenv

2. Setup the environment (.bashrc)

Code:
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bashrc

3. Update the environment

Code:
source ~/.bashrc

4. List the available version of python (about 700 to choose from)

Code:
pyenv install -l
2.1.3
...
3.12.1
..
3.13-dev
...

5. Install python (I use tcl/tk and have include these options, you may not need or want it)

Code:
PYTHON_CONFIGURE_OPTS="--with-tcltk-includes='-I/usr/local/include' --with-tcltk-libs='-L/usr/local/lib -ltcl8.6 -ltk8.6'" pyenv install 3.9.18

6. Set the version globally

Code:
pyenv global 3.9.18

7. Exit and re-enter the shell to test the environment

Code:
 python --version
Python 3.9.18

8. Create and activate a new virtual environment (your prompt will change to "(test) your original prompt" to indicate the venv is active).

Code:
python -m venv test
source test/bin/activate

9. Install juptyerlab and test it

Code:
pip install jupyterlab
jupyter lab

10. Celebrate success, troubleshoot problems if any, deactivate the environment (your prompt will change back to its original form).

Code:
deactivate

At this point, you should be good to go. If you want, install additional versions of python with

Code:
pyenv install VERSION

and switch between them with

Code:
pyenv global VERSION

or

Code:
pyenv local VERSION
 
Back
Top