Creating and Activating a Python Virtual Environment

Feb 19, 2024 9:34:21 PM

What is a Python Virtual Environment?

Python Virtual Environments are used to isolate Python software packages locally. By using a virtual environment, you can avoid installing Python packages globally which could break system tools or other projects. Ensure you have Python 3.10 or later installed on your system to proceed with the installation.

Using a Virtual Environment (‘venv’)

It’s recommended to use a virtual environment when working with Python projects. Once the environment is created, it must be activated to be usable.

  • The virtual environment resides inside the project folder and is named .venv.
  • Libraries installed in the virtual environment are not accessible outside of it.

Creating a Virtual Environment using Visual Studio Code

You can use Visual Studio Code to create and activate the virtual environment.

  1. Open the command palette and search for Python: Create Environment.
  2. Select the option and choose the project folder. This will create a .venv folder inside it.

By default, VS Code will automatically activate the virtual environment when you open the project folder. You can also manually activate it by opening the command palette and searching for Python: Select Interpreter.

You can view the current Python interpreter by looking at the lower right corner of the VS Code window.

Creating a Virtual Environment using the Command Line

Alternatively, you can create a new venv using the command line:

Activate the virtual environment using the activate file.

Command line activation is required each time you open a new terminal window. Make sure you activate your environment before running any Python commands.