How to make sure you call pip only in virtualenv?

2019-02-10 13:22发布

How to prevent accidentally calling pip when I am not in a virtualenv?

I wrote the following script called pipand added it to my ~/bin (which is before pip in my $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

Is there a better way?

2条回答
爷、活的狠高调
2楼-- · 2019-02-10 14:10
export PIP_REQUIRE_VIRTUALENV=true
查看更多
狗以群分
3楼-- · 2019-02-10 14:15

I'd recommend putting this in your ~/.bashrc file:

export PIP_REQUIRE_VIRTUALENV=true

and you can also add the following function to your ~/.bashrc that allows you to explicitly call pip outside of a virtual environment if you so choose:

gpip() {
   PIP_REQUIRE_VIRTUALENV="" pip "$@"
}

Now you can still use your global pip version for doing things like upgrading virtualenv:

gpip install --upgrade pip virtualenv
查看更多
登录 后发表回答