ubuntu下Python虛擬環境配置
阿新 • • 發佈:2019-02-19
Python虛擬環境配置
VirtualEnv用於在一臺機器上建立多個獨立的python執行環境,VirtualEnvWrapper為前者提供了一些便利的命令列上的封裝。
1.安裝virtualenv
pip install virtualenv #py2安裝
1.1 virtualenv建立虛擬環境並進入使用
說明文件
You must provide a DEST_DIR
Usage: virtualenv [OPTIONS] DEST_DIR
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-v, --verbose Increase verbosity.
-q, --quiet Decrease verbosity.
-p PYTHON_EXE, --python=PYTHON_EXE
The Python interpreter to use, e.g.,
--python=python2.5 will use the python2.5 interpreter
to create the new environment. The default is the
interpreter that virtualenv was installed with
(/usr/bin/python)
--clear Clear out the non-root install and start from scratch.
--no-site-packages DEPRECATED. Retained only for backward compatibility.
Not having access to global site-packages is now the
default behavior.
--system-site-packages
Give the virtual environment access to the global
site-packages.
--always-copy Always copy files rather than symlinking.
--unzip-setuptools Unzip Setuptools when installing it.
--relocatable Make an EXISTING virtualenv environment relocatable.
This fixes up scripts and makes all .pth files
relative.
--no-setuptools Do not install setuptools in the new virtualenv.
--no-pip Do not install pip in the new virtualenv.
--no-wheel Do not install wheel in the new virtualenv.
--extra-search-dir=DIR
Directory to look for setuptools/pip distributions in.
This option can be used multiple times.
--download Download preinstalled packages from PyPI.
--no-download, --never-download
Do not download preinstalled packages from PyPI.
--prompt=PROMPT Provides an alternative prompt prefix for this
environment.
--setuptools DEPRECATED. Retained only for backward compatibility.
This option has no effect.
--distribute DEPRECATED. Retained only for backward compatibility.
This option has no effect.
- 安裝需要版本的python
指定virtualenv中的python版本
virtualenv --no-site-packages --python=2.7 env
Note:
建立virtualenv虛擬環境之前,系統中必須要安裝有對應版本的python,並且解除安裝之後當前虛擬環境就無效了。系統中可以同時存在python2和python3,通過環境變數中的系統變數path(不是使用者變數)控制cmd或者系統中使用哪個版本的python,哪個版本的路徑在前面就優先使用哪個版本。
–no-site-packages表示不包括系統全域性的Python安裝包,這樣會更令環境更乾淨
–python=python2.7指定Python的版本未系統已經安裝了的Python2.7
env是建立的虛擬環境名稱
沒有安裝python2.7或者使用命令virtualenv –no-site-packages –python=python2.7 env會出現The executable python does notexist 錯誤
1.2進入虛擬環境並激活
$ . env/bin/activate
1.3退出虛擬環境
$ deactivate
1.4刪除虛擬環境
$ rm -r venv
2.virtualenvwrapper
2.1 pip安裝virtualenvwrapper
$ pip install virtualenvwrapper
2.2 初始化
將初始化檔案寫入使用者環境變數
$ vi .bashrc
# 加入下面兩行配置
source /usr/local/bin/virtualenvwrapper.sh
# 虛擬環境指定路徑,不指定預設使用~/.virtualenvs
export WORKON_HOME="虛擬環境絕對路徑"
- 建立:mkvirtualenv [虛擬環境名稱]
- 刪除:rmvirtualenv [虛擬環境名稱]
- 進入:workon [虛擬環境名稱]
- 退出:deactivate
所有的虛擬環境,都位於/home/.virtualenvs目錄下
建立指定版的虛擬環境:
yangqian@ubuntu:~$ mkvirtualenv -p python3.5 test-3.5