Visit dataquest for a more in-depth overview of what python virtual environments are, as well as what advantages they promise.

Creating a Python Virtual Environment (Windows)

py -m venv ['/path/to/new/virtual/environment']

Activating a Python Virtual Environment

['/path/to/new/virtual/environment']\scripts\activate

Installing Packages in a Python Virtual Environment

By default, only pip and setup tools are initially installed. To check the pre-installed packages:

pip list

To upgrade pip:

py -m pip install --upgrade pip

To install new packages:

py -m pip install pandas

Reproducing a Python Virtual Environment

You first need to list all the dependencies installed. Export the package list into a requirements.txt file

pip freeze > requirements.txt

Create a virtual environment, activate it, and then run:

pip install -r requirements.txt

Note:

If you’re going to add your project to a Git repository, never add its virtual environment folder to the repository. The only thing you need to add is the requirements.txt file.

A Python project folder contains source code that runs in a virtual environment. On the other hand, a virtual environment is a folder that contains the Python interpreter, packages, and tools like pip. So, the best practice is to keep them separate and never put your project files in a virtual environment folder.

Deactivating a Python Virtual Environment

deactivate

Deleting a Python Virtual Environment

If you want to delete a virtual environment, you can simply delete its folder, no uninstall required

rm -rf ['/path/to/new/virtual/environment']

Use Python Virtual Environments in Visual Studio Code

First, ensure you have created and activated a virtual environment.
Then navigate to your project folder in the terminal
and run the following command:

code .

The command above will open the project folder in VS Code. If the command above doesn’t work, open VS code, press command + shift + P, to open the Command Palette, type shell command and select Install ‘code’ command in PATH. Now, create a Python file, and name it my_script.py. The last step is to select the virtual environment using the Python: Select Interpreter command from the Command Palette. To do so, press Command + shift + P, and type Python, and choose Select Interpreter. The Python: Select Interpreter command displays all available environments.