我使用以下命令创建Python虚拟环境:
python3 -m venv venv3
要激活,我运行 source venv3/bin/activate
。
venv3/bin/activate
看起来并不复杂:
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "$_OLD_VIRTUAL_PATH" ] ; then
PATH="$_OLD_VIRTUAL_PATH"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "$_OLD_VIRTUAL_PYTHONHOME" ] ; then
PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then
hash -r
fi
if [ -n "$_OLD_VIRTUAL_PS1" ] ; then
PS1="$_OLD_VIRTUAL_PS1"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
if [ ! "$1" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
VIRTUAL_ENV="/home/pi/django-test/venv3"
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH
# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "$PYTHONHOME" ] ; then
_OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
unset PYTHONHOME
fi
if [ -z "$VIRTUAL_ENV_DISABLE_PROMPT" ] ; then
_OLD_VIRTUAL_PS1="$PS1"
if [ "x(venv3) " != x ] ; then
PS1="(venv3) $PS1"
else
if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
# special case for Aspen magic directories
# see http://www.zetadev.com/software/aspen/
PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
else
PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
fi
fi
export PS1
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then
hash -r
fi
我可以看到它会修改 $PATH 和 $PS1,创建一个 deactivate
函数,甚至备份旧的变量以便在用户运行 deactivate
函数时恢复它们。所有这些都很有道理。
唯一我没看到的是 Python 的 sys.path 被修改的地方。在我的系统上,我看到的是:
虚拟环境外的 sys.path:
['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-arm-linux-gnueabihf', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']
在虚拟环境中的sys.path:['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-arm-linux-gnueabihf', '/usr/lib/python3.5/lib-dynload', '/home/pi/django-test/venv3/lib/python3.5/site-packages']
很明显,sys.path在某个时刻以某种方式被修改了。这是有道理的,因为这就是Python知道在哪里找到已安装的第三方Python库的方法。我认为这是虚拟环境的主要功能,但我看不出它在哪里被设置了。
我并没有尝试去完成什么事情 - 大多数只是出于好奇。
sys.prefix
(它将引用虚拟环境)来初始化sys.path
。 - chepnersys.prefix
被设置为/usr
,而在虚拟环境内,它被设置为/home/pi/django-test/venv3
。是什么设置了这个变量?似乎activate
脚本并没有这样做。sys.path
如何使用这个变量? - Johnsys.prefix
的值是由 Python 自己决定的,基于解释器的安装位置。当你激活虚拟环境时,你的PATH
会被修改,以便python
解析为存储在你的虚拟环境目录中的可执行文件(可能只是一个符号链接)。 - chepner