Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Homebrew python taking precedence over venv python

I have a few questions related to Python paths. I used homebrew to install python3 on my Mac:

# homebrew python
> which -a python
python: aliased to /usr/local/bin/python3.9

# system python
❯ which -a python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
/usr/local/bin/python3
/usr/bin/python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3

I then set up a virtual environment using the command python -m venv venv. After activating it, I get:

> which -a python
python: aliased to /usr/local/bin/python3.9
/Users/kshitijsachan/Documents/venv/bin/python

> which -a python3
/Users/kshitijsachan/Documents/venv/bin/python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
/usr/local/bin/python3
/usr/bin/python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3

My questions are:

  1. Why does homebrew python take precedence over the venv python when I run which -a python with the venv activated?
  2. Why is /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 listed twice under which -a python3?
  3. Is this the canonical setup for venv's with Homebrew python?
like image 210
Kshitij Sachan Avatar asked Aug 16 '26 00:08

Kshitij Sachan


1 Answers

  1. I think Homebrew does not automatically alias python for you. You might have changed .bashrc file or something else yourself.
python: aliased to /usr/local/bin/python3.9

This line shows that python is aliased to /usr/local/bin/python3.9. Python venv only changes PATH variable, and alias is always prior to PATH, so you will not get the correct Python version.

To solve this, use command unalias python to unbind the alias in the current session. Also, check your .bashrc file (or .zsh_profile for MacOS zsh terminal), and remove the corresponding line. It should be like

alias python='/usr/local/bin/python3.9'

But be careful that after you do unalias, you should use python3 (or even python3.x for the specific version) instead of python. python command may refer to Python2 by default, depending on your OS.

  1. Not sure what causes this phenomenon. My output looks likes:
(.venv) $ which -a python3
.../test/.venv/bin/python3
/opt/homebrew/anaconda3/bin/python3
/Library/Frameworks/Python.framework/Versions/3.12/bin/python3
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3
/opt/homebrew/bin/python3
/usr/local/bin/python3
/usr/bin/python3
  1. Yes, venv is the official tool for creating a virtual environment.
python3 -m venv .venv  # create virtual env in .venv/
source .venv/bin/activate  # activate environment

The two commands above are often used to create and activate a virtual environment.

like image 197
OrthoPole Avatar answered Aug 17 '26 17:08

OrthoPole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!