Virtualenv

用户指导翻译自https://virtualenv.pypa.io/en/latest/user_guide.html

快速开始

创建环境(在当前目录下创建一个文件夹)

virtualenv env_name

在Linux或Mac系统中,激活新的Python环境

source env_name/bin/activate

在Windows系统中

\env_name\Scripts\activate

确认已成功选择该环境

which python3

介绍

Virtualenv有一个基本命令:

virtualenv venv

这将创建一个与virtualenv相同版本的Python虚拟环境,并将其安装到子目录venv中。命令行工具有许多标志可以修改工具的行为,要获取完整列表,请确保查看CLI标志。

该工具分为两个阶段:

  • 第一阶段是发现一个Python解释器,用于创建虚拟环境(默认情况下,这与virtualenv正在运行的Python相同,但我们可以通过 -p 选项来更改这一设置)。
  • 第二阶段在指定的目标位置(dest)创建一个虚拟环境,这可以分解为四个进一步的子步骤:
    • 创建一个与第一阶段目标Python解释器相匹配的Python。
    • 在创建的虚拟环境中安装(引导)种子包(pip、setuptools、wheel中的一个或多个)。
    • 将激活脚本安装到虚拟环境的二进制目录中(这将允许最终用户从各种shell中激活虚拟环境)。
    • 创建标记虚拟环境不受版本控制系统(目前仅支持Git,因为Mercurial、Bazaar或SVN不支持子目录中的忽略文件)影响的文件。可以使用no-vcs-ignore选项跳过此步骤。

你新的虚拟环境中的Python与创建它的Python实际上是隔离的。

Python 发现

我们创建虚拟环境所需的第一件事就是一个Python解释器。这将告诉工具你想创建什么类型的虚拟环境,可以将其视为:版本、架构、实现方式。

作为一个Python应用程序,virtualenv始终至少有一个可用的Python解释器,即virtualenv本身正在使用的解释器,因此这是默认的发现元素。这意味着,如果你在Python 3.8下安装了virtualenv,virtualenv将默认创建版本为3.8的虚拟环境。

创建的Python虚拟环境通常并非是自包含的。一个完整的Python软件包通常由成千上万个文件组成,因此将整个Python重新安装到一个新文件夹中并不高效。相反,虚拟环境只是一个外壳,其中包含的内容很少,大部分内容都是从系统Python(在安装Python本身时安装的内容)中借用的。这意味着,如果你升级了系统Python,你的虚拟环境可能会出现问题,所以要小心。但这样做的好处是,创建虚拟环境可以非常快速,因为它们引用了系统Python。

这里我们将描述内置机制(请注意,这可以通过插件进行扩展)。CLI标志 p 或 python 允许您指定一个Python规范,用于指定您想要的虚拟环境类型,格式可以是:

  • 一个相对/绝对路径指向一个Python解释器,
  • 一个指定Python实现、版本、架构的规范,格式如下:

    {Python实现名称}{版本号}{架构}

    我们有以下限制:

    Python实现只能包含字母字符(python代表任何实现,如果缺失则默认为python),

    版本是由点分隔的版本号,

    架构要么是-64,要么是-32(缺失表示任何)。

    例如:

    python3.8.1 代表任何Python实现版本号为3.8.1,

    3 代表任何Python实现主版本号为3,

    cpython3 代表CPython实现版本号为3,

    pypy2 代表PyPy实现主版本号为2的Python解释器。

    根据这个规范,virtualenv将采用以下策略来发现/找到系统可执行文件:

    • 如果我们在Windows操作系统上,会查看Windows注册表,并检查是否有任何注册的Python实现与规范匹配。这符合PEP-514    中所设定的期望。
    • 尝试在列举的PATH环境变量所包含的文件夹中发现一个与规范大致相似的Python可执行文件。在这种情况下,我们将尝试找到一个名字与规范大致相似的可执行文件(具体逻辑请参考实现代码)。

警告

如上所述,虚拟环境通常只是从系统Python中借用东西,它们实际上并不包含系统Python的所有数据。Python可执行文件中的版本是硬编码的。因此,如果您升级了系统Python,您的虚拟环境仍然会报告升级前的版本,即使除了可执行文件外,所有其他内容(标准库、二进制库等)都是新版本的。

除非出现重大不兼容性(这种情况很少发生),虚拟环境将继续正常工作,但除了Python可执行文件中嵌入的内容外,它将表现得像升级后的版本。如果将这样的虚拟环境Python指定为目标Python解释器,我们将创建与新系统Python版本匹配的虚拟环境,而不是虚拟环境报告的版本。

Creators

这些实际上是设置虚拟环境的内容,通常作为系统Python的参考。目前,virtualenv有两种类型的虚拟环境:

  • venv - this delegates the creation process towards the venv module, as described in PEP 405. This is only available on Python interpreters having version 3.5 or later, and also has the downside that virtualenv must create a process to invoke that module (unless virtualenv is installed in the system python), which can be an expensive operation (especially true on Windows).
  • builtin - this means virtualenv is able to do the creation operation itself (by knowing exactly what files to create and what system files need to be referenced). The creator with name builtin is an alias on the first creator that’s of this type (we provide creators for various target environments, that all differ in actual create operations, such as CPython 2 on Windows, PyPy2 on Windows, CPython3 on Posix, PyPy3 on Posix, and so on; for a full list see creator).

Seeders

这些将为您安装一些种子软件包(其中一个或多个:pip、setuptools、wheel),使您能够通过调用pip在创建的虚拟环境中安装额外的Python软件包。在Python 3.12+环境中,默认情况下禁用了安装setuptools和wheel。有两种主要的种子机制可用:

  • pip - this method uses the bundled pip with virtualenv to install the seed packages (note, a new child process needs to be created to do this, which can be expensive especially on Windows).
  • app-data - this method uses the user application data directory to create install images. These images are needed to be created only once, and subsequent virtual environments can just link/copy those images into their pure python library path (the site-packages folder). This allows all but the first virtual environment creation to be blazing fast (a pip mechanism takes usually 98% of the virtualenv creation time, so by creating this install image that we can just link into the virtual environments install directory we can achieve speedups of shaving the initial 1 minute and 10 seconds down to just 8 seconds in case of a copy, or 0.8 seconds in case symlinks are available - this is on Windows, Linux/macOS with symlinks this can be as low as 100ms from 3+ seconds). To override the filesystem location of the seed cache, one can use the VIRTUALENV_OVERRIDE_APP_DATA environment variable.

Wheels

要通过pip或app-data方法安装种子软件包,virtualenv需要获取目标软件包的wheel。这些wheel可以从多个位置获取,如下所示:

  • virtualenv ships out of box with a set of embed wheels for all three seed packages (pip, setuptools, wheel). These are packaged together with the virtualenv source files, and only change upon upgrading virtualenv. Different Python versions require different versions of these, and because virtualenv supports a wide range of Python versions, the number of embedded wheels out of box is greater than 3. Whenever newer versions of these embedded packages are released upstream virtualenv project upgrades them, and does a new release. Therefore, upgrading virtualenv periodically will also upgrade the version of the seed packages.
  • However, end users might not be able to upgrade virtualenv at the same speed as we do new releases. Therefore, a user might request to upgrade the list of embedded wheels by invoking virtualenv with the upgrade-embed-wheels flag. If the operation is triggered in such a manual way subsequent runs of virtualenv will always use the upgraded embed wheels.

    The operation can trigger automatically too, as a background process upon invocation of virtualenv, if no such upgrade has been performed in the last 14 days. It will only start using automatically upgraded wheel if they have been released for more than 28 days, and the automatic upgrade finished at least an hour ago:

    • the 28 days period should guarantee end users are not pulling in automatically releases that have known bugs within,
    • the one hour period after the automatic upgrade finished is implemented so that continuous integration services do not start using a new embedded versions half way through.

    The automatic behavior might be disabled via the no-periodic-update configuration flag/option. To acquire the release date of a package virtualenv will perform the following:

    • lookup https://pypi.org/pypi/<distribution>/json (primary truth source),
    • save the date the version was first discovered, and wait until 28 days passed.
  • Users can specify a set of local paths containing additional wheels by using the extra-search-dir command line argument flag.

When searching for a wheel to use virtualenv performs lookup in the following order:

  • embedded wheels,
  • upgraded embedded wheels,
  • 额外的搜索目录

Bundled wheels are all three above together. If neither of the locations contain the requested wheel version or download option is set will use pip download to load the latest version available from the index server.

Embed wheels for distributions

自定义分发通常希望使用自己的一组wheel版本进行分发,而不是使用virtualenv在PyPi上发布的版本。这样做的原因是为了保持这些软件包的系统版本与virtualenv使用的版本同步。在这种情况下,他们应该修补模块virtualenv.seed.wheels.embed,确保提供函数get_embed_wheel(根据分发/Python版本返回要使用的wheel)。如果他们想要使用virtualenv的测试套件进行验证,那么还需要BUNDLE_FOLDER、BUNDLE_SUPPORT和MAX变量。

此外,他们可能希望通过将virtualenv.seed.embed.base_embed.PERIODIC_UPDATE_ON_BY_DEFAULT修补为False来禁用定期更新,并让系统更新机制来处理这一点。需要注意的是,在这种情况下,用户仍然可以通过调用upgrade-embed-wheels来请求嵌入式wheels的升级,但不再会自动发生,并且不会改变操作系统提供的wheels。

Activators

这些是激活脚本,它们会修改您的shell设置,以确保在Python虚拟环境内部执行的命令优先于系统路径。例如,如果在shell中调用pip在激活之前返回系统Python的pip,那么一旦您进行激活,这应该指向虚拟环境的pip。需要注意的是,我们只是改变了优先级;因此,如果您的虚拟环境的bin/Scripts文件夹不包含某些可执行文件,那么在激活之前,它仍将解析为与激活之前相同的可执行文件。

有关我们提供的激活器列表,请参阅激活器。这些激活器的位置就在Python可执行文件旁边:通常在Windows上是Scripts文件夹,在POSIX系统上是bin文件夹。它们被称为activate,加上特定于激活器的扩展名,对于Bash来说则没有扩展名。您可以通过调用它们来激活它们,通常是通过source命令。source命令可能因shell而异 - 例如,在Bash中是source(或.):

source venv/bin/activate

激活脚本将虚拟环境的二进制文件夹添加到PATH环境变量之前。实际上,这只是为了方便,因为您自己也可以这样做。

请注意,您不必激活虚拟环境才能使用它。您可以使用其可执行文件的完整路径,而不是依赖于您的shell来将它们解析为您的虚拟环境。

激活器脚本还会修改您的shell提示符,通过在括号中添加环境名称(或在初始创建环境时指定的名称),如(venv),来指示当前活动的环境。您可以通过将环境变量VIRTUAL_ENV_DISABLE_PROMPT设置为任何值来禁用此行为。如果您想自定义提示符,您还可以通过环境变量VIRTUAL_ENV_PROMPT获取环境名称。

这些脚本还提供了一个deactivate命令,允许您撤消激活操作:

deactivate

Note

如果使用Powershell,激活脚本将受到系统上的执行策略的约束。默认情况下,在Windows 7及以后的版本中,系统的执行策略被设置为Restricted,这意味着不允许执行像激活脚本这样的脚本。

然而,这并不能阻止我们稍微改变一下,以允许执行它。您可以放宽系统执行策略,允许运行本地脚本而无需验证代码签名,方法如下:

Set-ExecutionPolicy RemoteSigned

由于activate.ps1脚本是针对每个虚拟环境在本地生成的,因此它不被视为远程脚本,可以被执行。

关于这一点的更详细解释可以在Allison Kaptur 2013年的博客文章中找到:《There’s no magic: virtualenv edition》。该文章解释了virtualenv如何使用bash和Python以及PATH和PYTHONHOME来隔离虚拟环境的路径。

Programmatic API 程序化API

目前,virtualenv只提供了命令行界面(CLI level interface)。如果你想在Python内部触发 Python 环境的调用,你应该使用 virtualenv.cli_run 方法;这个方法接受一个 args 参数,你可以像从命令行传递参数一样传递选项。运行后将返回一个包含有关创建的虚拟环境的数据的会话对象。

from virtualenv import cli_run

cli_run(["venv"])
virtualenv.cli_run(args, options=None, setup_logging=True, env=None)

根据一些命令行接口参数创建一个虚拟环境。

Parameters:

  • args – the command line arguments
  • options – passing in a VirtualEnvOptions object allows return of the parsed options
  • setup_loggingTrue if setup logging handlers, False to use handlers already registered
  • env – environment variables to use

返回:

创建的会话对象(目前其结构是实验性的,可能会在短期内发生变化)。

virtualenv.session_via_cli(args, options=None, setup_logging=True, env=None)

创建一个虚拟环境会话(与 cli_run 相同,但不执行创建)。如果你只想查询虚拟环境的外观,而不实际创建它,请使用这个。

Parameters:

  • args – the command line arguments
  • options – passing in a VirtualEnvOptions object allows return of the parsed options
  • setup_loggingTrue if setup logging handlers, False to use handlers already registered
  • env – environment variables to use

返回:

创建的会话对象(目前其结构是实验性的,可能会在短期内发生变化)

class virtualenv.run.session.Session(verbosity, app_data, interpreter, creator, seeder, activators)

代表一个虚拟环境创建会话。

属性 verbosity

运行的详细程度。

属性 interpreter

基于这个参考解释器创建虚拟环境。

属性 creator

用于构建虚拟环境的创建者(必须与解释器兼容)。

属性 seeder

提供种子软件包的机制(pip、setuptools、wheel)。

属性 activators

用于生成激活脚本的激活器。

“您的支持是我持续分享的动力”

微信收款码
微信
支付宝收款码
支付宝

目录