If you are new to software development and is now working with Python or trying to learn it, one of the most important concepts you must understand is the virtual environment.
In simple words, a virtual environment is a way to have multiple but isolated environments, all lying on the same computer where you can run your scripts or applications. Any Python application will be contained inside the virtual environment.
The reason for the existence of virtual environments is that every piece of software you create needs a different set of libraries and sometimes uses different versions of Python. The are situations when you need an specific version of a given library for your project and this version is different from the one you have on your system. A virtual environment will solve this for you.
This tutorial is for Ubuntu.
How to install virtualenv
You’ll need pip, that is used to install Python packages. If you don’t have it installed yet, run:
sudo apt install python-pip
Now, you can install virtualenv:
pip install virtualenv
Now you can create your virtual environment inside your projects folder.
Each project you are working on must have its own environment. It is a good practice.
Remember to add the environment folder to your .gitignore file if you use git or ignore it in your other prefered source version control tool.
First, cd into your project folder. I’ll use my_project as the project’s folder.
Now, create the environment. I’ll use the folder name my_env in this example.
Now you have a folder called my_env inside your my_project folder, with a copy of python and a copy of pip that you can use to install new libraries in this environment.
If you need to, you can instead specify which python version you want to use in your virtual environment. In this case, I’ll use the python3 executable I already have installed in my system.
virtualenv --python=/usr/bin/python3 my_env
How to activate the virtual environment in Python
To use your virtual environment you must activate it with the command:
From inside your my_project folder, run:
Now you are inside your virtual environment, isolated from the global python installed on your system. See the (my_env) on the command prompt indicating that.
Every package that you install now using pip will be installed inside the my_env folder.
Let’s give it a try:
pip install requests
Now, if you go inside the my_venv folder you’ll see the requests package there:
There are other similar ways to accomplish the same task and this video here explains in details how and why to do it. Please take 10 minutes to watch as it will represente a big step in your learning path:
For each project, create the requirements.txt file using pip freeze and save it to your repository. Next time you clone you project to work on it, just install everything inside the virtualenv using the requirements.txt file.