How to (and should I) put a path to user-installed python ahead of system-installed python?
I have a separate installation of Python 3.*, but the first python path in my $PATH
variable is the path to system-installed Python. Is this how it should be?
I have added the path to user-installed Python using https://www.architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.Uydjga1dXDg, and it was popped at the end of $PATH
.
Do I understand correctly that, in the current situation, when I run pip
, brew
etc. on python3 from bash, the changes will be applied to system-installed Python?
The fix I have got so far is to run export PATH=/usr/local/bin:/usr/local/sbin:$PATH
every time I want to install or
update python, but it is not ideal.
NB: I went with pyenv
solution as suggested by @bermudalocket. This pyenv tutorial was very useful.
Solution 1:
You can accomplish this by adding
export PATH="/path/to/python:"$PATH
to your ~/.zshrc
(or ~/.bash_profile
if you're not on Catalina).
I'd like to propose an alternative and suggest pyenv
, available via Homebrew. You can set a specific Python version to be "global" (i.e. default everywhere) and/or "local" (i.e. using that version in a specific directory only).
E.g.:
brew install pyenv
pyenv global 2.7.16
cd ~/myProjects/MyProject
pyenv local 3.7.6
If you were to use Python in ~/myProjects/MyProject
it will default to 3.7.6
, and anywhere else 2.7.16
:
cd ~/some/other/directory
python --version
>> Python 2.7.16
cd ~/myProjects/MyProject
python --version
>> Python 3.7.6
https://github.com/pyenv/pyenv#homebrew-on-macos
Solution 2:
I installed Python 3.8 for macOS using the installer from python.org, not homebrew which is also installed on my Mac but rarely used. I think the first three lines below to my ~/.bash_profile was automatically added by the installer from python.org.
With those, any changes I make using pip3
seem to affect only the 3.8 whereas those made via pip
seem to affect only the 2.7 (which I believe comes installed with macOS). Because I did not use homebrew in installing Python 3.8 (or 2.7), I assume it is not relevant for either version of Python in my case. Hope these help.
# Setting PATH for Python 3.8
PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:${PATH}"
export PATH
# Setting PATH for Python 2.7
# I believe the two lines below were already in the file before the above were added
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH