如何确保只在virtualenv中调用pip?

Mic*_*arf 7 python pip virtualenv

当我不在virtualenv时,如何防止意外调用pip?

我编写了以下脚本调用pip并将其添加到我的~/bin(在我的pip之前$PATH):

# This script makes sure I don't accidentally install pip without virtualenv
# This script requires $PIP to be set to the absolute path of pip to execute pip
# if $PIP is not set, it will write a message
if [ -z "$PIP" ]; then
   echo "you are not in a virtual env"
   echo "use virtual env or"
   # propose the second item in $PATH
   echo "  export PIP="`type -ap pip|sed -n 2p`
   echo "to cleanup use"
   echo "  unset PIP"
else
    # execute pip
    exec $PIP "$@"
fi
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

小智 9

export PIP_REQUIRE_VIRTUALENV=true
Run Code Online (Sandbox Code Playgroud)


Sam*_*ley 6

我建议将其放入您的~/.bashrc文件中:

export PIP_REQUIRE_VIRTUALENV=true
Run Code Online (Sandbox Code Playgroud)

并且您还可以向其中添加以下功能,~/.bashrc如果您愿意,可以在虚拟环境之外显式调用pip:

gpip() {
   PIP_REQUIRE_VIRTUALENV="" pip "$@"
}
Run Code Online (Sandbox Code Playgroud)

现在,您仍然可以使用全局pip版本执行诸如升级virtualenv之类的操作:

gpip install --upgrade pip virtualenv
Run Code Online (Sandbox Code Playgroud)