Skip to content

Instantly share code, notes, and snippets.

@identifysun
Last active March 2, 2020 10:18
Show Gist options
  • Save identifysun/e0a1f5e3b3f66cbc579403edc2983b70 to your computer and use it in GitHub Desktop.
Save identifysun/e0a1f5e3b3f66cbc579403edc2983b70 to your computer and use it in GitHub Desktop.

基于 Mac OS X Python 开发环境配置

Python 安装

使用 Homebrew 安装 Python

Homebrew 默认将安装 Python 3,Python 2.x 系列版本在 2020 年停止维护:

$ brew update
$ brew install python
$ python3 --version

使用 Pyenv 安装 Python

Pyenv 是 Python 的版本管理工具,你能通过使用 Pyenv 安装多个 Python 版本,并在多个版本间切换;

$ brew update
$ brew install pyenv

安装指定版本的 Python

$ pyenv install -l
$ pyenv install 2.7.17

切换 Python 版本到 2.7.17

$ pyenv global 2.7.17
$ which python
~/.pyenv/shims/python

https://github.com/yyuu/pyenv

虚拟环境管理工具

Python 虚拟环境管理工具,使用虚拟环境可以实现项目环境隔离,开发环境干净更易于维护;

一、使用 Pipenv 管理虚拟环境

Pipenv 是由 Pypa(Python Packaging Authority)开发的虚拟环境管理工具,底层封装了 virtualenv,因此你可以考虑使用 Pipenv 代替直接使用 virtualenv 工具;

使用 Homebrew 安装 Pipenv

$ brew install pipenv

关于 Pipenv 的用法,请参考 Pipenv 官方文档:https://github.com/pypa/pipenv

二、使用 Virtualenv + virtualenvwrapper 管理虚拟环境

Virtualenv,Python 环境的隔离工具,每个隔离环境可以有 Python 包的独立版本;vritualenv 将自动在家目录下创建如下目录: ~/.virtualenvs

virtualenvwrapper,推荐安装 virtualenvwrapper 包,virtualenv 的封装工具,更方便易用;

用法示例:

  1. 安装 Virtualenv + virtualenvwrapper
$ pip install virtualenv
$ pip install --user virtualenvwrapper
  1. 编辑 ~/.bash_profile 或 ~/.zshrc 文件,在文件末尾添加如下语句:
$ source /usr/local/bin/virtualenvwrapper.sh
  1. 为 registry-cli 项目创建虚拟环境,首先进入项目目录,并执行 mkvirtualenv 命令创建虚拟环境:
$ cd registry-cli
$ mkvirtualenv registry-cli
  • 使用 -p 参数指定虚拟环境 python 版本;
  1. 使用 deactivate 指令停止当前的工作环境;
$ deactivate
  1. 工作环境切换:
$ workon ENV
  1. 清理工作环境
$ rmvirtualenv ENV

Python 镜像站配置

Pip 配置文件路径

  • Linux/Unix:

    • /etc/pip.conf
    • ~/.pip/pip.conf
    • ~/.config/pip/pip.conf
  • Mac OSX:

    • ~/Library/Application Support/pip/pip.conf
    • ~/.pip/pip.conf
    • /Library/Application Support/pip/pip.conf
  • Windows:

    • %APPDATA%\pip\pip.ini
    • %HOME%\pip\pip.ini
    • C:\Documents and Settings\All Users\Application Data\PyPA\pip\pip.conf (Windows XP)
    • C:\ProgramData\PyPA\pip\pip.conf (Windows 7及以后)

修改 Pip 镜像源

$ cat > ~/.pip/pip.conf <<EOF
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
timeout = 60
EOF

参考文献

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment