Python: How to Use Virtual Environments

Python: How to Use Virtual Environments
Share on:

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

piplist

Create the virtual environment:

python3 -m venv "name of virtual environment"

i.e.: python3 -m venv myProjectEnv

It’ll take a few seconds to create the directory in your Homes folder.

Activate virtual environment:

source myProjectEnv/bin/activate

You’ll know when you’re in the virtual environment when the name of the project is indicated in parenthesis as below:

activate

Check which packages are installed in the newly created virtual environment”

pip list

If you want to install packages within that environment, i.e, requests and pytz, simply type in terminal:

pip install requests

pip install pytz

venvinstall

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:

pip freeze

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

venvfreeze

To deactivate the environment, just type in terminal:

deactivate

To delete the environment completely, type in terminal:

rm -rf myProjectEnv/

Create a virtual environment inside the project:

mkdir new_project

python3 -m venv new_project/venv

To activate the environment:

source new_project/venv/bin/activate

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.