How to Set Up Python Virtual Environments

Jenny ManJenny Man
19 min read

Maybe you’ve run into this before — you start a project with one library version, then update it for another project, and suddenly your original project breaks because it’s not compatible with the update. Or maybe you haven’t had to deal with that yet — great! This guide will help you keep it that way. That’s why virtual environments are so important, especially if you’re juggling multiple projects, collaborating with others, or getting ready to deploy your code. In this post, I’ll walk you through what virtual environments are, how to create and manage them, and how to get them up and running in Visual Studio Code, a code editor that allows you to write and manage code.


What is a Virtual Environment (VE)?

Think of a virtual environment like setting up your own cooking station in a shared kitchen. Imagine you are making a cake and someone else is making a spicy curry dish. If you both use the same kitchen tools and ingredients without cleaning up or separating things, you might accidentally end up with a cake that taste like spicy curry — not ideal!

What’s the solution? Set up a separate workstation just for your cake, with its own tools and ingredients. That way, nothing gets mixed up.

A virtual environment works the same way for coding. It gives each software project an isolated space with its own resources and dependencies, so nothing from one project interferes with another. It allows you to experiment and even make a mess while writing and testing your code — without worrying about affecting other projects or your main system.

A virtual environment is an isolated environment that allows you to manage dependencies and package versions for a project without interfering with other projects or the main system. This isolation reduces the risk of version conflicts.

When working with multiple projects, a virtual environment allows you to separate the dependencies of one project from another, especially if projects rely on different versions of a language or package. If you’re working with other people, it also ensures that anyone can install exactly the same dependency and package versions you used to make sure your program behaves consistently.

What are Python packages and libraries?
A library is a reusable collection of related codes that allow you to perform specific functions (e.g. data analysis or web development) without writing code from scratch. A package is the installable unit that delivers the library’s code. Once the package is installed, you can import the library’s codes to use its functionality in your program.

Python VE using Anaconda

I prefer this method because Anaconda lets you manage both packages and environments with the conda tool, and it makes it easy to create environments using any version of Python — even if that version isn’t installed on your system.

💡
Prerequisite: Anaconda or Miniconda installed on your system.

Creating a Conda Environment

A Conda environment is a self-contained virtual environment managed by Conda, a package and environment manager that helps you manage dependencies, packages, and Python versions without affecting your system-wide setup.

To create one, start by opening the Anaconda Prompt — just search for it in the Windows search bar. For convenience, you can pin it to your taskbar for quicker access next time.

When you open the Anaconda Prompt, you’ll notice (base) at the beginning of the line. This indicates that you’re using the default environment included with Anaconda. The base environment gives you access to a set of pre-installed libraries that come with Anaconda, but it operates independently from your system’s main Python installation.

Choosing a proper naming convention for your virtual environment is crucial for staying organized. The environment name should clearly reflect the project or task you’re working on, making it easy to identify which environments correspond to which project — especially if you are working with multiple projects or tasks. A helpful approach is to use a naming format like ‘project_name-env’, linking the environment directly to its purpose.

To create a Conda environment, run the conda command below:

# create Conda environment
conda create --name environment_name python=version # replace 'environment_name' and 'version'
conda create -n environment_name python=version # shorthand

To view a list of available Python versions to install from Conda, run the conda command below:

# displays a list of Python versions
conda search python

Example Workflow:

# search for available Python versions from Conda
conda search python

# create Conda environment with specific Python version
conda create -n demo_1-env python=3.12.5

After running the conda create command, Anaconda Prompt will display the location of where your Conda environment will be saved — by default, this is C:\Users\<YourUsername>\anaconda3\envs\. It will also list the packages that will be installed. To continue, press y and hit Enter to confirm the environment creation.

Immediately after creating a Conda environment, the Anaconda Prompt provides instructions on how to activate and deactivate your environment. You only need to create the virtual environment once. After that, you can simply activate it whenever you want to use it.

Managing a Conda Environment

How to View a List of Conda Environments

Use the command below to view a list of all Conda environments, check their locations, and highlight the active one (marked with an asterisk *):

# displays a list of virtual environments
conda env list

How to Activate or Deactivate a Conda Environment

List all environments to confirm the name of the one you want to activate or deactivate.

conda env list

Run the command below to activate or deactivate a virtual environment respectively:

# activate environment
conda activate environment_name # replace 'environment_name'

# deactivate environment
conda deactivate

Once you activate your Conda environment, you’ll see that the (base) prefix at the beginning of the Anaconda Prompt changes to (your_environment_name). This is a clear indicator of which virtual environment you’re currently working in. Any packages or Python versions you install will be confined to the activated environment and won’t affect the base Anaconda environment or your system globally.

When you deactivate your Conda environment, the prefix will change back to (base), indicating that you are working in Anaconda’s base environment.

How to Remove a Conda Environment

Deactivate the environment (if active).

conda deactivate

List all environments to confirm the name of the one you want to remove.

conda env list

Run one of the following commands to remove the environment:

# remove Conda environment
conda env remove --name environment_name # replace 'environment_name'
conda env remove -n environment_name # shorthand

How to Install and Manage Packages in a Conda Environment

Activate your Conda Environment.

conda activate environment_name # replace 'environment_name'

List all packages and versions installed in the active environment.

conda list

Install or change to a specific Python version:

# list all available python versions for install from Conda
conda search python 

# installs specific Python version
conda install python=version # replace 'version'

The commands below list several ways to install and manage packages:

# replace 'package_name' for all of the commands below

# install package of the newest version
conda install package_name

# list all available versions of a package from Conda
conda search package_name 

# install specific package version
conda install package_name=version # replace 'version'

# update the package to the newest version available from Conda
conda update package_name

# update all packages in the environment to the newest version
conda update --all

# remove a package
conda remove package_name

How to Save and Export Your Conda Environment to a Reusable File

List all environments to confirm the name of the one you want to save.

conda env list

When using Conda environments, it’s best to save packages and configuration details in a file called environment.yml to make it easy to recreate the same environment, whether for yourself or to share with others.

A full environment export captures everything in your environment — including manually installed packages, dependencies, exact versions, build numbers, and even OS-specific package variants (like Windows 64-bit or Ubuntu). This method is best when you need exact reproducibility, and your project is meant to run on a single operating system. Use the command below to create this type of export:

# exports the full environment
conda env export --name environment_name > environment.yml # replace 'environment_name'
conda env export -n environment_name > environment.yml # shorthand

A history-based export only captures the packages you explicitly installed — leaving out automatic dependencies, build numbers, and OS-specific package variants. This method is best if you plan to share the environment across different operating systems, and you want a minimal dependency list. Use the command below to create this type of export:

# exports a minimal environment
conda env export --name environment_name --from-history > environment.yml # replace 'environment_name'
conda env export -n environment_name --from-history > environment.yml # shorthand version

You can use an environment.yml file to recreate the setup of a Conda environment. Just make sure the file is in your working directory (main project folder) before running the command. Use the command below to create the environment from the file:

conda env create --file environment.yml 
conda env create -f environment.yml # shorthand

Example Workflow:

# navigate to a directory path to save the environment.yml file 
# (e.g. project's root folder)
cd "/directory/path/to/save/environment"

# save and export minimal Conda environment
conda env export -n project_1-env --from-history > environment.yml

# check that the environment.yml was created in the directory
dir

# replicate the Conda environment on another computer. 
conda env create -f environment.yml

# check for the new Conda environment name and path
conda env list

# activate the new environment
conda activate project_1-env

Saving the Conda environment details as an environment.yml file:

Recreating a Conda environment using the environment.yml file:

If you’re curious about what information is in the environment.yml, here it is opened in VS Code.

Summary of Commands for Conda Environments

Conda CommandsDescription
conda search pythonList Python versions available from Conda.
conda search package_nameList all versions of a package available from Conda.
conda create --name environment_name python=versionCreate a Conda environment with a specific python version.
conda env listList virtual environments, their locations, and highlights the active one (marked with an asterisk *).
conda listList all packages and versions installed in the active environment.
conda activate environment_nameActivate the specified virtual environment as your working environment.
conda deactivateDeactivate the current virtual environment.
conda env remove --name environment_nameRemove the specified virtual environment.
conda install python=versionInstall a specific Python version.
conda install package_nameInstall the newest version of a package.
conda install package_name=versionInstall a specific package version.
conda update package_nameUpdate a package to the newest version available from Conda.
conda update --allUpdate all packages in the virtual environment to the newest version available from Conda.
conda remove package_nameRemove the specified package.
conda env export --name environment_name > environment.ymlExport a full environment with all packages as a reusable environment.yml file.
conda env export --name environment_name --from-history > environment.ymlExport a minimal environment with explicitly installed packages as a reusable environment.yml file.
conda env create --file environment.ymlCreate a virtual environment from an environment.yml file. Make sure the file is in your working directory.

Python VE using Shell Command

Another way to create and manage virtual environments is by using Python’s built-in venv module and pip tool.

💡
Prerequisite: The venv module uses the version of Python it’s run with, so the version you want to use must already be installed on your system.

Creating a venv Environment

A venv environment is a virtual environment created using Python’s built-in venv module. This module is mainly used to create isolated environments, but it doesn’t manage them like Conda does.

To create one, start by pressing Windows+R, typing “cmd”, and pressing Enter. For convenience, you can pin it to your taskbar for quicker access next time.

Check your system’s default Python version to make sure it matches the version you want to use in your environment.

# use python command if you added python.exe to PATH during Python installation
python --version
python -V # shorthand

# use Python Launcher (py) if you did not add python.exe to PATH during Python installation
py --version
py -V # shorthand

To create a virtual environment using Python venv module, run one of the commands below — this will create the environment in the current working directory. Keep in mind that you can’t change the Python version once the environment is created, so be sure to choose the version you need before running the command.

# replace 'environment_name' for all the commands below.

# for system's default Python version
python -m venv environment_name # use python command
py -m venv environment_name # use python launcher (py) command

# for specific Python versions (use full path) 
"C:\path\to\python\interpreter\python.exe" -m venv environment_name 

# for specific Python versions using Python Launcher (py)
py -version -m venv environment_name # replace 'version'

To view a list of Python versions installed on your system and highlight the default version (marked with an asterisk *), run the following py command:

py -0

To confirm that the virtual environment was created using venv, check the pyvenv.cfg file (make sure you are in the parent folder of the virtual environment folder).

type environment_name\pyvenv.cfg # replace 'environment_name'

Example Workflow:

# check system's default Python version
python -V # or py -V

# view a list of Python versions installed on your system
py -0

# create a virtual environment with a specific Python version (use full path)
"C:\Users\UserName\Python\Python3.12.3\python.exe" -m venv project_2-venv

# check that the environment folder was created
dir

# confirm that the environment was created using venv module
type project_2-venv\pyvenv.cfg

Managing a venv Environment

How to Activate or Deactivate a venv Environment

Run the command below to activate or deactivate a venv environment:

# activate environment from the parent folder containing the environment folder
environment_name\Scripts\activate # replace 'environment_name'

# activate environment from anywhere
"full\path\to\environment"\Scripts\activate # replace 'full\path\to\environment'

# deactivate environment
deactivate

Once you activate your environment, you’ll see the prefix (your_environment_name) at the beginning of the Command Prompt. This is a clear indicator of which virtual environment you’re currently working in. Any packages or Python versions you install will be confined to the activated environment and won’t affect your system globally.

When you deactivate your environment, the prefix will disappear, indicating that you are working in your system environment.

How to Remove a venv Environment

Deactivate the environment (if active).

deactivate

Run the command below to remove the environment (make sure you are in the parent folder of the environment folder):

rmdir /s environment_name # replace 'environment_name'
# rmdir removes directories
# /s deletes all files and subfolders in the directory

How to Install and Manage Packages in a venv Environment

Virtual environments created with venv uses pip to install and manage Python packages.

Activate your virtual environment.

environment_name\Scripts\activate

List Python-specific packages and versions installed in the active environment.

pip list

The commands below list several ways to install and manage packages:

# replace 'package_name' for all of the commands below

# install python package of the newest version
pip install package_name

# list all available versions of a Python package
pip index versions package_name

# installs specific Python package version
pip install package_name==version # replace 'version'

# upgrade the Python package to the newest version
pip install --upgrade package_name

# uninstall a Python package
pip uninstall package_name

How to Save and Export Your venv Environment to a Reusable File

When using venv environments, it’s best to save packages and configuration details in a file called requirements.txt to make it easy to recreate the same environment. However, it does not include the Python version used, so you’ll need to add that manually if it’s important for your project.

Activate your venv environment.

environment_name\Scripts\activate # replace 'environment_name'

Use the command below to capture a list of all the Python packages installed in the activated environment:

pip freeze > requirements.txt # does not include python version. add it manually python==version

You can use a requirements.txt file to recreate the setup of a venv environment. Just make sure the file is in your working directory (main project folder) and that your virtual environment is activated before running the command. Use the command below to create the environment from the file:

pip install -r requirements.txt

Example Workflow:

# navigate to a directory path to save the requirements.txt file 
# (e.g. project's root folder)
cd "/directory/path/to/save/environment"

# activate your virtual environment
project_2-venv\Scripts\activate

# generate the requirements.txt file listing all installed packages
pip freeze > requirements.txt

# check that the requirements.txt was created in the directory
dir

# check the list of Python installed packages in the requirements.txt file
type requirements.txt

# create a new virtual environment on another computer
C:\Users\UserName\Python\Python3.12.3\python.exe -m venv project_2-venv

# activate the virtual environment
project_2-venv\Scripts\activate

# install the packages from the requirements.txt file
pip install -r requirements.txt

# check that the virtual environment folder was created
dir

# check the Python-specific packages and versions installed in the active environment
pip list

Saving the venv environment details as a requirements.txt file:

Recreating a venv environment using the requirements.txt file:

Summary of Commands for venv Environments

CommandsDescription
python --versionCheck your system default Python version if you added python.exe to PATH during installation.
py --versionCheck your system default Python version using Windows Python Launcher.
py -0List Python versions installed on your system and highlight the default version (marked with an asterisk *).
python -m venv environment_nameCreate virtual environment with the system default Python version.
py -m venv environment_nameCreate virtual environment with the system default Python version using Windows Python Launcher.
"C:\path\to\python\interpreter\python.exe" -m venv environment_nameCreate virtual environment with a specific Python version (use full path of interpreter). Use double quotes around path if any folder name has spaces.
py -version -m venv environment_nameCreate virtual environment with a specific Python version using Windows Python Launcher.
dirList the contents of the current directory.
type environment_name\pyvenv.cfgCheck that the environment was created using venv module.
environment_name\Scripts\activateActivates the virtual environment. Make sure to be in the parent folder of the environment folder.
"full\path\to\environment"\Scripts\activateActivate virtual environment from anywhere.
deactivateDeactivate virtual environment.
rmdir /s environment_nameRemove a virtual environment (make sure to be in the parent folder of the environment folder)
pip listList Python-specific packages and versions installed in the active environment.
pip index versions package_nameList all available versions of a Python package.
pip install package_nameInstall the newest version of a Python package.
pip install package_name==versionInstall a specific package version.
pip install --upgrade package_nameUpgrade a Python package to the newest version.
pip uninstall package_nameUninstall a Python package.

Add VE to VS Code

The most reliable way to connect a virtual environment to VS Code is by creating and activating your virtual environment from the terminal and then launching VS Code from there. This ensures that the shell environment in VS Code is set up correctly; it recognizes your virtual environment. Then, select the correct Python interpreter in VS Code to make sure all of its tools — like the debugger, code runner, and the terminal — use the right environment.

💡
Prerequisite: Command-line must be able to run code commands. You might need to add the ‘code’ command to your PATH if it doesn’t recognize it.

Step 1: Switch VS Code Default Terminal to Command Prompt

By default, VS Code uses PowerShell as its terminal, but this can cause issues when trying to activate virtual environments because of PowerShell’s security restrictions. The easiest solution is to switch the terminal to Command Prompt in VS Code.

  • Launch VS Code

  • Open the Command Palette: Ctrl+Shif+P

  • Type: “Terminal: Select Default Profile”

  • Select Command Prompt

  • Verify that Command Prompt (CMD) is the default terminal by opening a new terminal and confirming it shows “cmd”.

Step 2: Create and Activate the Virtual Environment

  • Open your terminal: Anaconda Prompt or Command Prompt

  • Navigate to your project’s folder:

      cd "path/to/your/project" # use double quotes if any folder name contains spaces
    
  • Create the virtual environment:

      # for Conda environment
      # saves environment in default location: C:\Users\<YourUsername>\anaconda3\envs\
      conda create --name environment_name python=version # replace 'environment_name' and 'version'
    
      # for venv environment
      # saves environment in current working directory
      "C:\path\to\python\interpreter\python.exe" -m venv environment_name # replace 'environment_name'
    
  • Activate the virtual environment:

      # for Conda environment
      conda activate environment_name # replace 'environment_name'
    
      # for venv environment
      environment_name\Scripts\activate # replace 'environment_name'
    

Step 3: Launch VS Code from the Same Terminal

  • Launch VS Code:

      code .
    

    Note: If code command isn’t recognized by your terminal, you might need to add the ‘code’ command to your PATH.

Step 4: Select the Python Interpreter in VS Code

  • Open the Command Palette: Ctrl+Shift+P

  • Type and select: “Python: Select Interpreter**”**

  • Choose the interpreter that matches your environment or enter the full path if it doesn’t show up.

Step 5: Verify the Environment is Set Up Correctly

These are steps to verify that your VS Code environment is synced with your virtual environment.

  • Check the Terminal Prefix:

    View terminal inside VS Code (View > Terminal or Ctrl+` )

    You should see the virtual environment name in parentheses at the start of the terminal line.

  • Check the Python Execution Path:

    Create a python file in VS Code by hovering next to your project folder and clicking the “New File…” icon.

    Name your file with the .py extension.

    Type the following code in the editor area and save it (Ctrl+S):

      import sys
      print(sys.executable)
    

    On the top-right, click the drop-down arrow next to the code runner icon and select Run Python File in Dedicated Terminal.

    In the terminal, you should see the Python executable path that points to your environment.

  • Look at the VS Code Status Bar:

    At the bottom corner of VS Code, you’ll see the Python interpreter as the name of your virtual environment.

    If it’s incorrect, click it to reopen the Python interpreter selector and select the correct one.


I hope this guide has helped you understand what a virtual environment is, why it’s important, and how to create and use one for your projects! It’s always a good idea to set up a virtual environment before starting any projects. By doing so, you’ll avoid potential issues with dependency and package conflicts, making your coding experience smoother.

Thanks so much for reading! If you enjoyed the read, feel free to share it. Wishing you the best of luck on your coding journey!

Majority of my new posts from here on out will be about my Python coding journey. If you’re interested, please follow and subscribe to my newsletter 😊!

0
Subscribe to my newsletter

Read articles from Jenny Man directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jenny Man
Jenny Man

I'm starting my journey as a programmer with a focus on Python and test automation. Experience in quality assurance, test case design, and defect management. Passionate about driving product quality and continuous learning in the tech field.