Purpose: to have a space or “environment” to install packages for a specific project
- if working on a project using a older version of a technology, i.e. Nodejs, and it was time to upgrade to a new version, that update might break the project
Creating the virtual environment via terminal:
First, do a
pip3 list to see what packages are installed system wide
Create the virtual environment:
python3 -m venv "name of virtual environment"
python3 -m venv myProjectEnv
It’ll take a few seconds to create the directory in your Homes folder.
Activate virtual environment:
You’ll know when you’re in the virtual environment when the name of the project is indicated in parenthesis as below:
Check which packages are installed in the newly created virtual environment”
If you want to install packages within that environment, i.e, requests and pytz, simply type in terminal:
pip install requests
pip install pytz
In case you want to export your packages of that specific environment, to be used in a different project, just create a requirements.txt file, useful if the same packages and versions are needed.
In terminal, type:
This will provide a list of packages in correct format to be exported in a txt file somewhere else by using greater than sign “>”
pip freeze > requirements.txt
To deactivate the environment, just type in terminal:
To delete the environment completely, type in terminal:
rm -rf myProjectEnv/
Create a virtual environment inside the project:
python3 -m venv new_project/venv
To activate the environment:
Now, we can install the same packages we had in the previously created requirements.txt file:
pip install -r requirements.txt
It’s not recommended to add any porjects in the virtual environment folder (“venv”). One should be able to completely remove the virtual environment, at any time, without affecting the project files.