About virtualenv #
Hello, you!
Virtualenv is a tool to create isolated environments in Python. With a virtual environment, you don’t have to install packages globally, so it helps to reduce compatibility issues.
It has its own installation directories and doesn’t share libraries even with other virtualenv environments.
Installation #
First, install pip
. Make sure you have it upgraded. Next, install virtualenv
. Prefer to use python3 -m pip
instead of just pip
, as the Python documentation suggests.
$ sudo apt install pip
$ python3 -m pip install --upgrade pip
$ python3 -m pip install virtualenv
You may end up receiving a message similar to this:
WARNING: The scripts pip, pip3, pip3.10 and pip3.9 are installed in ‘/home/jessica/.local/bin’ which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use –no-warn-script-location.
If you’re using Bash on Linux, all you need to do is to export the path to your ~/.bashrc
file and reload it.
$ echo -e 'export PATH="$PATH:/home/jessica/.local/bin"' >> /home/jessica/.bashrc
$ source /home/jessica/.bashrc
Next time you run pip, you’ll not get the message anymore.
Setting the environment #
Go to your project’s directory. We’ll set the virtual envorinment and call it venv
.
$ python3 -m virtualenv venv
Your venv is set and there should be a folder inside your project named venv
. So, whenever you want to activate the environment, you just have to use the activate script.
$ source venv/bin/activate
It’ll show something like (venv)
next to your user on the shell prompt.
If you’re using git, don’t forget to add the folder to gitignore.
$ echo 'venv' >> .gitignore
As you finish installing packages to your project, you must generate their info to the requirements file.
$ python3 -m pip freeze > requirements.txt
So if you need to run the venv on another system, as you install pip and virtualenv again, you’ll just need one command to install all the requirements for your project.
$ python3 -m pip install -r requirements.txt
If you finish and want to exit the environment, just go to the root of the project and use the deactivate script.
$ deactivate
For now, that’s it. Pretty simple and very much useful.
Installing packages #
You can have a look at PyPi and explore the existing packages you now can use with your project in a simpler way, without worrying if you have every package installed on your system.
Having the environment activated, you can install a package by using the first command below. You can also install a specific version of the package.
$ python3 -m pip install --user package_name
$ python3 -m pip install --user package_name==0.3
The --user
is needed to install the packages isolated to the current user.
After installing a package, remember to update the requirements file.
And you’re set, I think. You can look for further information on the virtualenv documentation.
Hope it helps.