Using a virtual environment

Every time you start a project involving Python code it is important to create a virtual environment. This allows you to manage the installation and updating of Python packages that are needed for your project without interfering with packages used by the system or by other projects.

There are several benefits to using a virtual environment:

The steps below show you how to create a virtual environment with Python’s built-in venv module and install a package within it.

Create

Open the Terminal in VS Code and navigate to your project folder. Then run the command below. The -m tells Python to use the venv module to create a virtual environment in a folder called venv. You can call the virtual environment whatever you like though.

python -m venv venv

This will create a bin subdirectory in your project folder containing a copy of the Python interpreter and some supporting files.

Activate

To start using the virtual environment and manage packages you need to activate it.

venv\Scripts\activate
source venv/bin/activate

The environment name will appear in brackets next to the command line.

Check Python version

Now that your are in a virtual environment you can check the version of Python that you are using.

python --version

Install packages

To install a package just run the following command substituting pandas for the package that you want.

python -m pip install pandas

The installed package will appear in the Lib folder.

Run Python script

python script.py

Reproducibility

It is good practice to create a (requirements.txt) text file which contains all of the packages used in a project. This allows collaborators to reproduce your results using the same package versions.

python -m pip freeze > requirements.txt

Users can install all of the project’s package with python -m pip install -r requirements.txt.

Deactivate

To close your virtual environment just type:

deactivate

The environment name will no longer appear in brackets.

Delete

If you want to delete your virtual environment from your project folder you can do it manually or in the command line.

rmdir /s /q venv
rm -rf venv