Mastodon hachyterm.io

Create isolated Python projects with virtual environments

What is a virtual environments and why should I use it?

A virtual environment allows you to develop several Python projects with different versions of packages on the same computer.
Python usually installs the latest versions of your dependencies globally. You’ll run into problems, if one of your projects requires a different package version.

venv

Python ships with venv out of the box since version 3.3.

Inside your Python project folder, run the following code in your terminal:

python3 -m venv <name-of-your-virtual-environment>

Now you have to activate the environment:

source <name-of-your-virtual-environment>/bin/activate

If you use the fish shell, use this command:

source <name-of-your-virtual-environment>/bin/activate.fish

Inside the virtual environment, you can use pip (or even better: pipx) to install packages:

pip install <package-name>

Exit the environment with deactivate:

source deactivate

virtualenv

virtualenv is a more powerful tool than the standard venv. You can run different Python versions on the same machine, you can relocate a virtual environment, etc.

Make sure that pip is installed on your computer. Run:

pip install virtualenv

(or pip install --user virtualenv)

Now you can create a virtual environment in your Python project:

virtualenv <virtual-environment-name>

You have to switch to the environment with

source <virtual-environment-name>/bin/activate

virtualfish

virtualfish is a wrapper around virtualenv for the fish shell.

You can install it with pip:

pip install virtualfish

Edit ~/.config/fish/config.fish and add the following line:

eval (python -m virtualfish)

You can also add plugins, for example, the auto_activation plugin, which automatically switches to the virtual environment.

eval (python -m virtualfish auto_activation)

You should also modify your fish prompt. Edit ~/.config/fish/functions/fish_prompt.fish and add the following code inside the function body:

if set -q VIRTUAL_ENV
    echo -n -s (set_color -b blue white) "(" (basename "$VIRTUAL_ENV") ")" (set_color normal) " "
end

Now you can use virtualfish in the terminal:

vf new <name-of-the-virtual-environment>
vf activate
vf deactivate