How to prevent accidentally calling pip when I am not in a virtualenv?
I wrote the following script called pip
and 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?
To create a virtual environment, go to your project's directory and run venv. If you are using Python 2, replace venv with virtualenv in the below commands. The second argument is the location to create the virtual environment. Generally, you can just create this in your project and call it env .
The virtualenv program enables you to create custom Python environments, while the pip program enables you to install Python packages. By using these programs, you can ensure your Python applications have the exact environment setup that they need to function correctly.
In this example, you run pip with the install command followed by the name of the package that you want to install. The pip command looks for the package in PyPI, resolves its dependencies, and installs everything in your current Python environment to ensure that requests will work.
You can list only packages in the virtualenv by pip freeze --local or pip list --local . This option works irrespective of whether you have global site packages visible in the virtualenv .
export PIP_REQUIRE_VIRTUALENV=true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With