python環境神器virtualenvwrapper安裝與使用

virtualenv與virtualenvwrapper

當涉及到python項目開發時爲了避免污染全局環境,一般都會使用環境隔離管理工具virtualenvvirtualenvwrapperpython

virtualenv是在項目底下執行生成venv環境目錄以此來進行管理,這很是適合使用諸如pycharm這種集成環境配置的開發工具;那麼當經過shell來運行virtualenv時便會顯得很是麻煩,由於每次shell關閉再打開後都須要從新配置環境參數。shell

virtualenvwrapper是將全部的python項目虛擬環境環境都存放在一塊兒,在使用shell配合小型開發工具就會很是方便。vim

virtualenvwrapper安裝配置(MAC)

  1. 使用pip3安裝bash

    $ sudo pip3 install virtualenvwrapper
  2. 新建存放環境目錄(筆者目錄爲Envs並放在Home下)app

    $ mkdir -p ~/Envs
  3. 配置virtualenvwrapper環境(使用python3)框架

    i. 打開bash_profile,執行vim ~/.bash_profile並寫入工具

    # 設置virtualenvwrapper
    export WORKON_HOME=~/Envs
    export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
    # 打開終端自動啓用
    source /usr/local/bin/virtualenvwrapper.sh

    ii. 打開.zshrc,執行vim ~/.zshrc並寫入(若是有安裝item2oh-my-zsh)post

    # 設置virtualenvwrapper
    export WORKON_HOME=~/Envs
    export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
    # 打開終端自動啓用
    source /usr/local/bin/virtualenvwrapper.sh
  4. 使配置生效開發工具

    $ source ~/.bash_profile
    $ source ~/.zshrc

virtualenvwrapper 使用

  1. 新建虛擬環境test並指定python版本python3ui

    $ mkvirtualenv test --python=python3

    執行lsvirtualenv指令查看全部環境,環境test位於~/Envs/test

    $ lsvirtualenv
    test
    ====
  2. 在項目底下激活虛擬環境test

    workon test
  3. 其餘指令

    ## 退出環境test
    deactivate
    ## 刪除環境test
    rmvirtualenv test
    ## 更多指令能夠在shell中輸入virtualenv回車會有提示

virtualenvwrapper設置環境變量

當咱們使用框架時常常須要執行pip install或者 export環境變量等額外的操做,這時就須要使用postactivate等鉤子文件(固然鉤子文件還有不少,具體感興趣能夠去查看官方文檔)。

舉個栗子:

想在test虛擬環境激活後設置環境變量

  1. 打開testpostactivate鉤子文件vim ~/Envs/test/bin/postactivate

    #!/bin/zsh
    # This hook is sourced after this virtualenv is activated.
    
    # 在當前會話加入環境變量
    export ENV=dev
  2. 這時當執行workon test 激活虛擬環境後便會執行postactivate將項目環境變量Env設置爲dev
  3. postactivate 中還能夠執行諸如pip install -r requirements.txtpip install -e confshell 操做

到目前爲止基本的virtualenvwrapper使用就介紹完了

原文地址:http://www.fidding.me/article/71

happy coding!
相關文章
相關標籤/搜索