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:
- it is stable with no package version conflicts
- it improves reproducibilty with all packages and their versions listed in a
requirements.txtfile - your project is contained in a single folder and is therefore portable
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 venvThis 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\activatesource venv/bin/activateThe 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 --versionInstall packages
To install a package just run the following command substituting pandas for the package that you want.
python -m pip install pandasThe installed package will appear in the Lib folder.
Run Python script
python script.pyReproducibility
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.txtUsers can install all of the projectβs package with python -m pip install -r requirements.txt.
Deactivate
To close your virtual environment just type:
deactivateThe 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 venvrm -rf venv