确定 Python 是否在 virtualenv 中运行 [英] Determine if Python is running inside virtualenv

查看:56
本文介绍了确定 Python 是否在 virtualenv 中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以确定当前脚本是否在 virtualenv 环境中运行?

解决方案

最可靠的检查方法是检查是否sys.prefix == sys.base_prefix.如果它们相等,则您不在虚拟环境中;如果他们不平等,你就是.在虚拟环境中,sys.prefix 指向虚拟环境,sys.base_prefix 是创建 virtualenv 的系统 Python 的前缀.

以上始终适用于 Python 3 stdlib venv 和最近的 virtualenv(自版本 20).旧版本的 virtualenv 使用 sys.real_prefix 而不是 sys.base_prefix(并且 sys.real_prefix 在外部不存在一个虚拟环境),并且在 Python 3.3 和更早版本中 sys.base_prefix 不存在.因此,处理所有这些情况的完全稳健的检查可能如下所示:

导入系统def get_base_prefix_compat():"""获取基本/真实前缀,如果没有,则获取 sys.prefix.""";返回 getattr(sys, "base_prefix", None) 或 getattr(sys, "real_prefix", None) 或 sys.prefixdef in_virtualenv():返回 get_base_prefix_compat() != sys.prefix

如果您只关心支持的 Python 版本和最新的 virtualenv,您可以将 get_base_prefix_compat() 替换为简单的 sys.base_prefix.>

使用 VIRTUAL_ENV 环境变量是不可靠的.它由 virtualenv activate shell 脚本设置,但是通过直接从 virtualenv 的 bin/(或 Scriptscode>) 目录,在这种情况下 $VIRTUAL_ENV 将不会被设置.或者,当在 shell 中激活 virtualenv 时,可以直接执行非 virtualenv Python 二进制文件,在这种情况下,$VIRTUAL_ENV 可能会在 Python 进程中设置,而该进程实际上并未在该 virtualenv 中运行.>

Is it possible to determine if the current script is running inside a virtualenv environment?

解决方案

The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix points to the virtual environment, and sys.base_prefix is the prefix of the system Python the virtualenv was created from.

The above always works for Python 3 stdlib venv and for recent virtualenv (since version 20). Older versions of virtualenv used sys.real_prefix instead of sys.base_prefix (and sys.real_prefix did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix did not ever exist. So a fully robust check that handles all of these cases could look like this:

import sys

def get_base_prefix_compat():
    """Get base/real prefix, or sys.prefix if there is none."""
    return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix

def in_virtualenv():
    return get_base_prefix_compat() != sys.prefix

If you only care about supported Python versions and latest virtualenv, you can replace get_base_prefix_compat() with simply sys.base_prefix.

Using the VIRTUAL_ENV environment variable is not reliable. It is set by the virtualenv activate shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv's bin/ (or Scripts) directory, in which case $VIRTUAL_ENV will not be set. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV may be set in a Python process that is not actually running in that virtualenv.

这篇关于确定 Python 是否在 virtualenv 中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆