Mac上python2和python3的版本切换设置

Posted by Yuankun Li on 2020-06-10

安装Python

如果你正在使用Mac,系统是OS X>=10.9,那么系统自带的Python版本是2.7。要安装最新的Python 3.9,有两个方法:

方法一:从Python官网下载安装程序

从Python官网下载Python 3.9的安装程序
从Python官网下载Python 2.7.18 (python2最后一个版本)

下载后双击运行并安装:

安装目录:

1
2
3
4
which python3
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3
# python2
/Library/Frameworks/Python.framework/Versions/2.7/bin/python2

方法二:Homebrew

如果安装了Homebrew,直接通过命令brew install python3安装即可。

安装目录:/usr/local/Cellar/python@3.9
可执行文件目录:/usr/local/bin/python3.9

MAC Monterey 系统上新版本Homebrew, 例如 3.3.12,默认路径变为/opt/homebrew/Cellar/python@3.10, 下面的子目录就是用brew安装的其他包。

查找Python路径

根据你实际的python安装路径,进行下一步的Environment path的设置。

Mac 自带python 路径

1
2
which python
/usr/bin/python

从Python官网下载Python 3.9的安装程序安装路径

1
2
which python3
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3

查看python版本

1
python -V

设置Python路径

按这篇Python笔记:Mac上python2和python3的版本切换的简单处理方式的方法设置:

修改bash_profile

1
vi ~/.bash_profile

如果使用zsh则相应修改~/.zprofile

1
vi ~/.zprofile
1
2
3
4
5
6
7
8
9
10
# Setting PATH for Python 2.7
# The original version is saved in .bash_profile.pysave
export PATH="/usr/bin:${PATH}"

# Setting PATH for Python 3.9
# The original version is saved in .bash_profile.pysave
export PATH="/Library/Frameworks/Python.framework/Versions/3.9/bin:${PATH}"

# If you using Homebrew to install Python 3
# export PATH="/usr/local/bin:${PATH}"

修改bashrc

1
vi ~/.bashrc

如果使用zsh则相应修改~/.zshrc

1
vi ~/.zshrc
1
2
3
4
5
6
# python
alias python2='/usr/bin/python2.7'
alias python3='/Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9'
# If you using Homebrew to install Python 3
# alias python3='/usr/local/bin/python3.9'
alias python=python3

使设置生效:

1
source ~/.bashrc

设置完后

设置完后:

1
2
3
4
5
6
7
8
$ python -V
Python 3.8.0
$ which python2
python2: aliased to /usr/bin/python2.7
$ which python3
python3: aliased to /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9
$ which python
python: aliased to python3

切换Python版本

修改.bashrc文件中的刚添加的最后一行
修改 alias python=python3 或者改为alias python=python2

使设置生效:

1
source ~/.bashrc

命令行报错 command cannot found pip

1
2
$ pip install wakatime
command cannot found pip

Maybe you have installed both python2 and python3. python3 may have been installed later.

You may try to use pip3 instead of pip.

First, input the command:

pip3 -V
If you see the version, the pip3 can be used.

In case you do

which pip
and it doesn’t show the path, just do

which pip3
This will print the path which is /usr/local/bin/pip3

Then do open ~/.zshrc or nano ~/.bash_profile.

Make alias for pip like:

1
alias pip=/usr/local/bin/pip3

N.B: You copy that line above and paste in your .zshrc file.

After do source ~/.zshrc and close .zshrc



show git comment