Reputation: 31
For a school project I had to work with a Python venv.
This was not the first time, but when I initialised and activated the venv and did pip list
it showed my entire global package collection.
So I recursively deleted the whole thing and thought it would be best to simply reinstall all the essentials (numpy, pandas, etc.) globally again and then install only specifics where needed.
Then I found out that no matter where I installed (with venv activated or not), it would always just download globally.
No matter where I pip list
ed, it would always show the whole thing.
This got me to think that I might have never gotten venvs to work.
I always do:
python3 -m venv venv
source venv/bin/activate
and it will show (venv)
before the little arrow (or $) implying it works, but it clearly doesn't.
What am I missing?
I am on a M1 MacBook Air, using zsh (oh-my-zsh, but I don't think that should make a difference), Python 3.10.
edit: It turned out to only be the case in one specific venv. When creating another venv the expected behaviour returned. Still not sure what was the problem though.
Upvotes: 2
Views: 1716
Reputation: 499
First of all, you want to check which python interpreter is referred to when running python3
: to do so, run which python3
(this should return path/to/env/bin/python3
if your env was successfully activated)
Each time you want to install a package in your virutal env, make sure to run python3 -m pip install my_package
instead of pip install my_package
: this will make sure that my_package
will be installed for the python interpreter associated to your environment.
Finally, in order to avoid installing by mistake any package on your global python interpreter, add this to your .bashrc
/ .zshrc
:
export PIP_REQUIRE_VIRTUALENV="true"
This will raise an error each time you try to install a package to the global interpreter. In order to keep the option to install packages globally, I define the following command additionally:
gpip() {
PIP_REQUIRE_VIRTUALENV="" pip "$@"
}
and run gpip install my_package
to install it globally.
Upvotes: 1