Don't use sudo pip install
If you use sudo pip install black
, it will pollute your global Python installation. You don't want to do that.
You also don't need to use --system-site-packages
in your virtualenvs. You can use it for other reasons, but using it just so that black
etc. can work is a bad idea.
Intermediate solution: Use pip install --user
Deactivate your virtualenv, then execute pip install --user black
(--user
is the default in many systems when pip
isn't in a venv/virtualenv and isn't run as root). This will install black
somewhere in the user's home directory, such as $HOME/.local
.
You will subsequently be able to run black
regardless which venv/virtualenv you have activated, and regardless whether the venv/virtualenv has been created with --system-site-packages
.
Why this works: If you wanted to import black
in your code, this wouldn't work in a venv/virtualenv (unless with --system-site-packages
), because black
is installed "system-wide", albeit in a user's home dir ("user-wide" would be a more correct term in this case). However you don't want to import black
; what you want is to execute the black
command, and this will work regardless which venv/virtualenv you have activated, because to your shell black
is just a command it can find in the path, just like ls
or more
(it's in $HOME/.local/bin
, which should be in the PATH
). This is true of pretty much everything you want to install "system-wide" (i.e. outside of any venv/virtualenv): shell commands like black
, flake8
and pytest
.
If you look at $HOME/.local/bin/black
, you'll see that its first line is something like #!/usr/bin/python3
. This means it uses the system-wide python installation and not a venv/virtualenv. (If it was #!/usr/bin/env python
then it would use the activated venv/virtualenv instead.)
Best solution: Use pipx
The problem with the above solution is that it pollutes your "user-wide" python installation, which is almost like polluting your system-wide installation. You can do this instead (with venvs/virtualenvs deactivated):
pip install --user pipx
pipx install black
What pipx
does is it creates a venv specifically for black
and installs black
in that venv. The $HOME/.local/bin/black
executable that it creates is such that it runs black
in that venv. pipx uninstall black
removes both the executable and the venv.
Further reading
If there's still something unclear, my article virtualenv demystified may help.
--system-site-packages
when creating a virtualenv – Astylarpython -m venv --system-site-packages .venv/dev
– Ovipositor