我已经使用发行版的软件包管理器在全球范围内安装了IPython。从虚拟环境启动它时,会收到消息UserWarning: Attempting to work in a virtualenv. …
。我尝试使用florisla在Determine if Python is running inside virtualenv上描述的方法来确定其是否正常运行。我实际上正在运行的代码部分进行了稍微修改,以在运行时打印出所有布尔值:
# 1) VIRTUAL_ENV environment variable
# Both 'virtualenv' and 'venv' set the environment variable '$VIRTUAL_ENV' when activating an environment. See PEP 405.
# You can read out this variable in shell scripts, or use this Python code to determine if it's set.
import os
running_in_virtualenv = "VIRTUAL_ENV" in os.environ
# alternative ways to write this, also supporting the case where
# the variable is set but contains an empty string to indicate
# 'not in a virtual environment':
running_in_virtualenv1a = bool(os.environ.get("VIRTUAL_ENV"))
running_in_virtualenv1b = bool(os.getenv("VIRTUAL_ENV"))
# The problem is, this only works when the environment is activated by the 'activate' shell script.
# You can start the environment's scripts without activating the environment, so if that is a concern, you have to use a different method.
print("1a:", running_in_virtualenv1a)
print("1b:", running_in_virtualenv1b)
# 2) sys.real_prefix and sys.base_prefix
# Virtualenv points 'sys.prefix' to the Python installed inside of the virtualenv as you would expect.
# At the same time, the original value of 'sys.prefix' is also made available as a new attribute of 'sys': 'sys.real_prefix'. This is what we're using to detect if we're in a virtualenv.
import sys
running_in_virtualenv = hasattr(sys, "real_prefix")
# There's a problem though: 'venv' and 'pyvenv' do this differently from 'virtualenv' -- they don't set 'real_prefix'. Instead, they set 'base_prefix' to a different value from 'sys.prefix'.
# So to be safe, check both as suggested in hroncok's answer:
import sys
virtualenv_prefix = getattr(sys, "real_prefix", None)
venv_prefix = getattr(sys, "base_prefix", sys.prefix)
running_in_virtualenv2 = virtualenv_prefix or venv_prefix != sys.prefix
print("2:", running_in_virtualenv2)
现在,如果我从虚拟环境外部运行此代码,则我的False
外壳和python3
都会得到三个ipython3
,但是如果我在虚拟环境中, IPython返回最后一个布尔值(False
)的running_in_virtualenv2
,而python3
返回所有布尔值的True
。
我是否仍可以使用IPython在虚拟环境中进行修补,而不会增加系统安装的风险?
答案 0 :(得分:1)
大多数虚拟环境是关于修改导入搜索路径的。
import pprint
import sys
pprint.pprint(sys.path)
在不同的环境中检查path
,
并选择一个与您的venv相对应的目录元素,
例如,当您
输入$ which python
。
让您的代码根据状态更改其行为
该目录的地址。