Python - Windows系统下安装使用virtualenv

1 - virtualenv

https://pypi.python.org/pypi/virtualenv/
https://github.com/pypa/virtualenv

在实际开发测试中,每个应用很可能需要不同的Python开发和运行环境、引用不同的依赖、设置不同的权限。
随着应用的增多,不同应用间必然会产生依赖冲突、Python版本冲突以及间接权限问题。
利用virtualenv工具可以针对每个应用创建一套“隔离的、纯净的”Python开发和运行环境,能够独立地使用Python环境和管理库,从而很好地解决以上问题。
创建并激活一个virtualenv环境时,virtualenv会修改相关环境变量,让命令python和pip均指向当前的virtualenv环境。
创建虚拟环境的过程,实际上是将系统Python环境复制成为一个拥有独立安装目录的虚拟Python环境,这个环境不影响系统Python环境,也不影响其他虚拟环境。

2 - 安装使用virtualenv

当前环境描述:Window7-x64系统同时安装了Python2.7和Python3.6,并且将Python2.7作为主环境,两个版本各自都已安装很多第三方库。

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\guowli>py -2 -V
Python 2.7.12

C:\Users\guowli>py -3 -V
Python 3.6.0

C:\Users\guowli>python -V
Python 2.7.12

C:\Users\guowli>

2.1 - 安装virtualenv

1- pip安装

C:\Users\guowli>pip install virtualenv --proxy="10.144.1.10:8080"
Collecting virtualenv
  Using cached virtualenv-15.1.0-py2.py3-none-any.whl
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0

C:\Users\guowli>pip show virtualenv
Name: virtualenv
Version: 15.1.0
Summary: Virtual Python Environment builder
Home-page: https://virtualenv.pypa.io/
Author: Jannis Leidel, Carl Meyer and Brian Rosner
Author-email: python-virtualenv@groups.google.com
License: MIT
Location: c:\python27\lib\site-packages
Requires:

C:\Users\guowli>

注意:在Python3的环境中使用“pip3 install virtualenv --proxy="10.144.1.10:8080"命令安装和使用“pip3 show virtualenv”命令查看包信息。

2- 源码安装

2.2 - 创建虚拟环境

注意:

  • 创建虚拟环境可能需要几分钟,请耐心等待。
  • 参数“-p”:指定虚拟环境的Python解释器版本;需使用绝对路径。
  • 参数“--no-site-packages”:创建“纯净”的Python运行环境(已安装的第三方包不复制到虚拟环境)。
  • 参数“--system-site-packages”: 当前系统Python环境的所有库也会安装在虚拟环境。
  • 创建虚拟环境成功后,会生成对应名称的目录文件。系统类型不同,目录文件也略有区别。
  • 创建的虚拟环境不能跨平台使用。

示例: 创建名称为VenPy3、解释器为Python3.6、纯净的(没有任何第三方包)虚拟环境。

D:\Anliven-Running\Zen\TestEnvPython>virtualenv -p c:\Python36\python.exe --no-site-packages VenvPy3
Running virtualenv with interpreter c:\Python36\python.exe
Using base prefix 'c:\\Python36'
New python executable in D:\Anliven-Running\Zen\TestEnvPython\VenvPy3\Scripts\python.exe
Installing setuptools, pip, wheel...done.

D:\Anliven-Running\Zen\TestEnvPython>dir
 Volume in drive D is DATA
 Volume Serial Number is 3479-3F1E

 Directory of D:\Anliven-Running\Zen\TestEnvPython

2017/12/05  16:37    <DIR>          .
2017/12/05  16:37    <DIR>          ..
2017/12/05  16:37    <DIR>          VenvPy3
               0 File(s)              0 bytes
               3 Dir(s)  76,200,370,176 bytes free

D:\Anliven-Running\Zen\TestEnvPython>source
'source' is not recognized as an internal or external command,
operable program or batch file.

D:\Anliven-Running\Zen\TestEnvPython>dir VenvPy3\
 Volume in drive D is DATA
 Volume Serial Number is 3479-3F1E

 Directory of D:\Anliven-Running\Zen\TestEnvPython\VenvPy3

2017/12/05  16:37    <DIR>          .
2017/12/05  16:37    <DIR>          ..
2017/02/13  10:59    <DIR>          Include
2017/12/05  16:37    <DIR>          Lib
2017/12/05  16:43    <DIR>          Scripts
2017/12/05  16:37    <DIR>          tcl
               0 File(s)              0 bytes
               6 Dir(s)  76,200,370,176 bytes free

D:\Anliven-Running\Zen\TestEnvPython>

目录解释
   - lib:所有python库的安装位置为“lib/pythonx.x/site-packages/”目录;inux系统对应为“bin”目录。
   - bin:bin/python是在当前环境使用的python解释器

2.3 - 激活虚拟环境

虚拟环境Script目录下的activate脚本用来激活当前虚拟环境,可直接执行deactivate关闭(去激活)当前虚拟环境。
注意:激活后,

  • 在虚拟环境下,用pip安装的包都被安装到这个环境,系统Python环境不受任何影响。
  • 命令行提示符前,将显示生效的虚拟环境名称。
  • 虚拟环境作用于当前终端的所有目录;关闭当前终端,虚拟环境也同时关闭。
  • deactivate命令可以在任意目录直接执行。
D:\Anliven-Running\Zen\TestEnvPython\VenvPy3\Scripts>dir
 Volume in drive D is DATA
 Volume Serial Number is 3479-3F1E

 Directory of D:\Anliven-Running\Zen\TestEnvPython\VenvPy3\Scripts

2017/12/05  16:43    <DIR>          .
2017/12/05  16:43    <DIR>          ..
2017/12/05  16:43             2,223 activate
2017/12/05  16:43               783 activate.bat
2017/12/05  16:43             8,325 activate.ps1
2017/12/05  16:43             1,137 activate_this.py
2017/12/05  16:43               508 deactivate.bat
2017/12/05  16:42            98,194 easy_install-3.6.exe
2017/12/05  16:42            98,194 easy_install.exe
2017/12/05  16:42            98,166 pip.exe
2017/12/05  16:42            98,166 pip3.6.exe
2017/12/05  16:42            98,166 pip3.exe
2017/12/05  16:37           100,504 python.exe
2017/12/05  16:37         3,555,992 python36.dll
2017/12/05  16:37            98,968 pythonw.exe
2017/12/05  16:42            98,173 wheel.exe
              14 File(s)      4,357,499 bytes
               2 Dir(s)  76,200,140,800 bytes free

D:\Anliven-Running\Zen\TestEnvPython\VenvPy3\Scripts>activate

(VenvPy3) D:\Anliven-Running\Zen\TestEnvPython\VenvPy3\Scripts>python -V
Python 3.6.0

(VenvPy3) D:\Anliven-Running\Zen\TestEnvPython\VenvPy3\Scripts>cd ../../../

(VenvPy3) D:\Anliven-Running>pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a
 format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
pip (9.0.1)
setuptools (28.8.0)
wheel (0.29.0)

(VenvPy3) D:\Anliven-Running>deactivate
D:\Anliven-Running>python -V
Python 2.7.12

D:\Anliven-Running>

注意:Linux系统下,激活命令类似于“source ./bin/activate”

2.4 - 在虚拟环境中安装依赖

使用pip命令安装依赖,操作与系统Python环境相同。
依赖会安装到“lib/pythonx.x/site-packages/”目录;Linux系统对应为“bin”目录下。
可以使用-r requirements.txt批量安装依赖

pip freeze  #显示所有已安装的依赖
pip freeze > requirement.txt  #生成包含所有已安装的依赖信息的requirement.txt文件
pip install -r requirement.txt  #批量安装依赖

2.5 - 删除虚拟环境

直接删除虚拟环境目录和文件。

3 - virtualenv帮助信息

D:\Anliven-Running\Zen>virtualenv -h
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
                        (c:\python27\python.exe)
  --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.

D:\Anliven-Running\Zen>

4 - 安装使用virtualenvwrapper-win

https://pypi.python.org/pypi/virtualenvwrapper
https://pypi.python.org/pypi/virtualenvwrapper-win
virtualenvwrapper是virtualenv的一层封装,提供了一些便利命令行,适用于Linxu系统。
virtualenvwrapper-win适用于Windows系统。
可以直接安装virtualenvwrapper-win,同时virtualenv作为依赖也将被安装。

4.1-安装virtualenvwrapper-win

D:\Anliven-Running\Zen>pip install virtualenvwrapper-win --proxy="10.144.1.10:8080"
Collecting virtualenvwrapper-win
  Downloading virtualenvwrapper_win-1.2.4-py2-none-any.whl
Requirement already satisfied: virtualenv in c:\python27\lib\site-packages (from virtualenvwrapper-win)
Installing collected packages: virtualenvwrapper-win
Successfully installed virtualenvwrapper-win-1.2.4

D:\Anliven-Running\Zen>
D:\Anliven-Running\Zen>pip show virtualenvwrapper-win
Name: virtualenvwrapper-win
Version: 1.2.4
Summary: Port of Doug Hellmann's virtualenvwrapper to Windows batch scripts
Home-page: https://github.com/davidmarble/virtualenvwrapper-win/
Author: David Marble
Author-email: davidmarble@gmail.com
License: BSD 3-clause
Location: c:\python27\lib\site-packages
Requires: virtualenv

D:\Anliven-Running\Zen>

4.2-设置环境变量

virtualenvwrapper-win默认虚拟环境目录指向用户文件夹的Envs目录,需要改为实际的虚拟环境保存目录。

D:\Anliven-Running\Zen\TestEnvPython>lsvirtualenv

dir /b /ad "C:\Users\guowli\Envs"
==============================================================================
File Not Found

D:\Anliven-Running\Zen\TestEnvPython>

控制面板--->系统--->属性--->高级系统设置--->环境变量。新建系统变量并保存,虚拟环境的保存路径WORKON_HOME,重启终端。

C:\Users\guowli>lsvirtualenv

dir /b /ad "D:\Anliven-Running\Zen\TestEnvPython"
==============================================================================
testPy3.6
VenvPy3

C:\Users\guowli>

4.3-常用命令及示例

Main Commands : https://pypi.python.org/pypi/virtualenvwrapper-win

lsvirtualenv        # 列出WORKON_HOME目录下已有的虚拟环境
mkvirtualenv <name>        # 创建虚拟环境 
rmvirtualenv <name>        # 删除虚拟环境
workon <name>        # 激活虚拟环境,在不同的虚拟环境间切换
deactivate       # 关闭(去激活)虚拟环境

mkvirtualenv帮助信息:

C:\Users\guowli>mkvirtualenv --help

Usage: mkvirtualenv [mkvirtualenv-options] [virtualenv-options] DEST_DIR

  DEST_DIR              The name of the envirnment to create (must be last).

The new environment is automatically activated after being
initialized.

mkvirtualenv options:
  -a project_path       Associate existing path as project directory
  -i package            Install package in new environment. This option
                        can be repeated to install more than one package.
  -r requirements_file  requirements_file is passed to
                        pip install -r requirements_file

    NOTE: all mkvirtualenv-options must come before virtualenv-options!

示例:

C:\Users\guowli>mkvirtualenv -p c:\Python27\python.exe --no-site-packages testPy2.7
Running virtualenv with interpreter c:\Python27\python.exe
New python executable in D:\Anliven-Running\Zen\TestEnvPython\testPy2.7\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(testPy2.7) C:\Users\guowli>pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a
 format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
pip (9.0.1)
setuptools (28.8.0)
wheel (0.29.0)

(testPy2.7) C:\Users\guowli>deactivate

C:\Users\guowli>
C:\Users\guowli>lsvirtualenv

dir /b /ad "D:\Anliven-Running\Zen\TestEnvPython"
==============================================================================
testPy2.7
testPy3.6
VenvPy3

C:\Users\guowli>
C:\Users\guowli>rmvirtualenv VenvPy3

    Deleted D:\Anliven-Running\Zen\TestEnvPython\VenvPy3


C:\Users\guowli>
C:\Users\guowli>workon testPy2.7
(testPy2.7) C:\Users\guowli>
(testPy2.7) C:\Users\guowli>workon testPy3.6
(testPy3.6) C:\Users\guowli>
(testPy3.6) C:\Users\guowli>deactivate
C:\Users\guowli>

5 - 在PyCharm中使用virtualenv(推荐)

PyCharm本身已集成virtualenv工具,无需手工安装,可以创建并为项目设置指定的虚拟环境。
PyCharm文档:https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html#configuring-venv

创建方式一:新建项目时创建虚拟环境
File--》New Project--》Pure Python--》点击Interpreter参数栏右侧齿轮图标并选择“Create VirtualEnv”--》根据选择填写Name、Location和Base interpreter。

创建方式二:在当前项目创建虚拟环境
File--》Settings--》Project:xxx--》Project Interpreter,点击参数栏右侧齿轮图标并选择“Create VirtualEnv”--》根据选择填写Name、Location和Base interpreter。
勾选“Make available to all projects”参数,可以使虚拟环境都所有项目都起作用。
勾选“Inherit global site-packages”参数,将继承当前系统Python环境的所有库。

6 - 其他

Linux下安装使用virtualenv和virtualenvwrapper的方法与Windows基本一致,只是在环境变量设置和激活虚拟环境命令上有细微差别。

posted @ 2017-12-06 22:47  Anliven  阅读(1461)  评论(0编辑  收藏  举报