Blog / Technology /

16 October 2026

How to Create Virtual Environment in Python: A Practical Guide for Developers

A Python script can work perfectly in one project and fail in another, even on the same computer. Often, the problem is not the code. It is the environment running it.

One application might need an older version of a library, while another depends on a newer release. Installing both projects’ requirements into the same Python installation creates a shared dependency problem. Upgrading a package for one application can quietly break the other.

A virtual environment gives each project its own package installation space. It makes dependencies easier to manage, problems easier to diagnose, and projects easier to hand over.

This guide explains how to create virtual environment in Python on Windows, macOS, and Linux. More importantly, it explains how to confirm that your terminal, package installer, and editor are using the environment you intended.

What Is a Virtual Environment in Python?

A Python virtual environment is a directory containing an environment-specific Python executable, configuration files, installed packages, and supporting scripts.

It is created from an existing Python installation. By default, third-party packages installed in one environment are isolated from those installed in another.

For example, imagine maintaining two applications:

  • A reporting application that depends on an older library release.

  • A new automation tool that requires a newer release of the same library.

Separate environments allow both applications to keep their required dependencies without competing for a single installed version. Python provides the built-in venv module for creating these environments.

A virtual environment does not provide a separate operating system. It also does not sandbox your application’s access to files, networks, or system resources. Its main purpose is Python dependency isolation.

That distinction matters: installing an untrusted package inside .venv does not make that package safe.

Why Use a Virtual Environment for Every Project?

For a small script with no external dependencies, an isolated environment may seem unnecessary. Once a project starts installing packages, however, the benefits become clear.

Prevent dependency conflicts

Two applications can use different package versions without requiring you to repeatedly uninstall and reinstall them.

Keep project requirements understandable

A clean environment contains packages installed for that project. This makes dependency records more useful than a list exported from a global installation containing years of unrelated tools.

Make upgrades easier to evaluate

You can recreate an environment, install updated dependencies, and test the application before changing the setup used for regular work.

Reduce setup problems during collaboration

When the project documents its Python version and dependencies, another developer has a clearer path to running it.

The professional habit is straightforward: create a Python virtual environment before installing project dependencies.

Before You Start: Check Your Python Installation

Open a terminal and confirm that Python is available.

Windows

Try:

py --version

If your installation does not provide the py command, try:

python --version

macOS and Linux

Run:

python3 --version

Use the command that resolves to your intended Python installation.

Do not assume that python, python3, and py always select the same interpreter. On a computer with multiple installations, they may resolve differently.

Before creating the environment, inspect the interpreter path:

Windows:

py -c "import sys; print(sys.executable)"

macOS or Linux:

python3 -c "import sys; print(sys.executable)"

The selected interpreter determines the Python version used to create the environment. Creating .venv does not download whichever Python version your project needs. That version must already be available.

How to Create Virtual Environment in Python

Start by creating a project directory and moving into it:

mkdir inventory_tool

cd inventory_tool

Keep your source code in this project directory. The environment will live in a separate subdirectory.

Create the environment on Windows

Run:

py -m venv .venv

If you use python instead of py:

python -m venv .venv

Create the environment on macOS or Linux

Run:

python3 -m venv .venv

Here is what the command means:

ComponentPurpose
python3, python, or pySelects the Python interpreter
-mRuns a module using that interpreter
venvCreates the isolated environment
.venvNames the destination directory

The directory name .venv is a convention. You can choose another name, but consistency helps developers and tools recognise its purpose.

Your application files should sit beside .venv, rather than inside it. Treat the environment as something you can rebuild without losing source code.

How to Activate Virtual Environment in Python

Creating an environment and activating it are separate operations.

Creation builds the directory and supporting files. Activation adjusts your current shell so commands such as python resolve to the environment’s interpreter.

The activation command depends on your shell:

Platform and shellActivation command
Windows PowerShell.\.venv\Scripts\Activate.ps1
Windows Command Prompt.venv\Scripts\activate.bat
macOS or Linux, Bash/Zshsource .venv/bin/activate
macOS or Linux, Fishsource .venv/bin/activate.fish

You may see (.venv) added to your terminal prompt after activation.

Activation affects the current shell session. Opening a separate terminal does not automatically activate the same environment unless your development tools are configured to do so. You can also use an environment without activating it by calling its Python executable directly.

Understanding how to activate virtual environment in Python therefore requires knowing which shell you are using, not just which operating system you have.

Activate Virtual Environment Python Windows: Which Command Works?

If you searched for activate virtual environment python windows, the practical answer is:

PowerShell:

.\.venv\Scripts\Activate.ps1

Command Prompt:

.venv\Scripts\activate.bat

Run the command from your project directory. If .venv lives elsewhere, adjust the path.

Using a Bash activation command in PowerShell, or a PowerShell command in Command Prompt, is a common reason activation fails.

What If PowerShell Blocks the Activation Script?

PowerShell may report that running scripts is disabled.

First, inspect the applicable policies:

Get-ExecutionPolicy -List

On a machine where you are permitted to change the session policy, you can use:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

Then retry:

.\.venv\Scripts\Activate.ps1

The Process scope applies to the current PowerShell session. Organisation-managed policies can take precedence, so a session-level change will not necessarily override them.

You can also skip activation and run:

.\.venv\Scripts\python.exe -m pip --version

For application execution:

.\.venv\Scripts\python.exe app.py

This gives you an explicit interpreter path without requiring an activation script.

Verify That the Correct Environment Is Running

A changed prompt is useful feedback, but the interpreter itself gives stronger evidence.

After activation, run:

python -c "import sys; print(sys.executable)"

The result should point inside your project’s .venv directory.

Next, inspect the package installer:

python -m pip --version

Its reported installation path should also belong to .venv.

These two checks answer different questions:

  • Which Python executable will run the application?

  • Which Python installation will receive packages?

Make them part of your troubleshooting routine. If an import fails immediately after installation, check these paths before reinstalling anything.

An installation can succeed while targeting a different interpreter from the one running your code.

Install Packages Using the Environment’s Python

With the environment active, install a package:

python -m pip install requests

The python -m pip pattern explicitly runs pip through the selected Python interpreter. This reduces ambiguity compared with calling a standalone pip command whose location may differ.

For an interactive development setup, you can update pip with:

python -m pip install --upgrade pip

Then inspect installed packages:

python -m pip list

Verify that the example package imports:

python -c "import requests; print(requests.__version__)"

The Python Packaging User Guide uses this interpreter-based approach for installing packages into an environment.

Avoid installing every potentially useful package at the beginning. Add dependencies when the project needs them. A smaller dependency set is easier to understand, maintain, and rebuild.

Run a Real Script Inside the Virtual Environment

Create a file named app.py in your project directory:

import sys

 

import requests

 

 

def main():

    request = requests.Request(

        method="GET",

        url="https://example.com",

    )

    prepared = request.prepare()

 

    print(f"Python executable: {sys.executable}")

    print(f"Requests version: {requests.__version__}")

    print(f"Prepared request: {prepared.method} {prepared.url}")

 

 

if __name__ == "__main__":

    main()

Run it:

python app.py

This example prepares an HTTP request without sending it. It verifies that your application can import an installed dependency and shows which interpreter executes the file.

Check the output carefully. The executable path should reference .venv.

This small diagnostic is more valuable than assuming the environment works because package installation completed without errors.

Save Dependencies in requirements.txt

Once the application has the packages it needs, record the installed versions:

python -m pip freeze > requirements.txt

Another environment can install those recorded dependencies with:

python -m pip install -r requirements.txt

However, understand what this file represents.

pip freeze reports installed packages in requirements format. It does not compute a lockfile or determine which dependencies your application directly needs.

For example, installing one library may also install several dependencies. A frozen requirements file records those installed packages too.

For a small application, this is a useful starting point. For a larger project, distinguish between:

  • Dependencies the application explicitly requires.

  • Supporting dependencies installed by those packages.

  • Development tools used for testing, linting, or documentation.

Also record the Python version separately. Matching package versions does not guarantee matching behaviour across different Python versions, operating systems, or system libraries.

Recreate the Environment on Another Computer

When sharing a project, share its source code and dependency information.

The receiving developer should:

  1. Install the documented Python version.

  2. Open a terminal in the project directory.

  3. Create a new .venv.

  4. Activate it using the appropriate shell command.

  5. Install the recorded requirements.

  6. Run the application and its checks.

For example, on macOS or Linux:

python3 -m venv .venv

source .venv/bin/activate

python -m pip install -r requirements.txt

python app.py

On Windows PowerShell:

py -m venv .venv

.\.venv\Scripts\Activate.ps1

python -m pip install -r requirements.txt

python app.py

This workflow also gives you a useful maintenance check: can the project still start from a clean environment?

If it works only in one long-lived environment, the project may depend on undocumented packages, local files, or machine-specific configuration.

Use a Specific Python Version

Sometimes the application requires a particular Python release.

If Python 3.12 is installed and available through the Windows launcher, for example:

py -3.12 -m venv .venv

On macOS or Linux, where the corresponding executable is installed:

python3.12 -m venv .venv

After activation, verify:

python --version

Python 3.12 here is an example of explicit version selection, not a requirement for every project.

Choose the version supported by your application and dependencies. When testing a different Python release, create a separate environment so you can compare results without disturbing the working setup.

Connect the Environment to Your Code Editor

A terminal and an editor can use different interpreters.

That explains a familiar problem: the application runs in the terminal, but the editor reports a missing import or fails when you press Run.

In VS Code with Python tooling installed:

  1. Open the project folder.

  2. Open the Command Palette.

  3. Run Python: Select Interpreter.

  4. Choose the interpreter inside .venv.

  5. Run the script and inspect sys.executable again.

VS Code provides environment discovery and interpreter selection through its Python tooling.

For other editors, look for the project interpreter or Python SDK setting.

If you use notebooks, check the selected notebook kernel separately. Selecting the right terminal interpreter does not prove that an already-running notebook kernel uses it.

Common Virtual Environment Problems and Their Fixes

Python is not recognised

Try the platform-appropriate alternatives: py or python on Windows, and python3 on macOS or Linux.

If none works, resolve the Python installation or executable path before attempting to create the environment.

The activation file cannot be found

Confirm that your terminal is in the project directory and that environment creation completed successfully.

Also check whether you named the environment .venv, venv, or something else. The activation path must match the actual directory.

A package is installed, but the import fails

Compare:

python -c "import sys; print(sys.executable)"

python -m pip --version

python -m pip show requests

If the package is absent from the selected environment, install it there.

If it is present, check the import name. Package distribution names and Python import names do not always match.

Also check whether your own file shadows a package. Naming a script requests.py, for example, can interfere with importing the real library.

The environment stopped working after a folder move

Recreate it at the new location and reinstall the requirements.

Environment files and installed scripts can contain paths tied to the original location. Copying the directory is therefore an unreliable migration strategy.

Package installation reports incompatible requirements

Read the resolver’s explanation. Determine which dependency constraints conflict and which Python versions the packages support.

Repeatedly reinstalling the same incompatible versions will not resolve the underlying constraint problem.

Keep the Environment Out of Git

Add an environment exclusion to the project’s .gitignore:

.venv/

__pycache__/

*.pyc

Commit the application code, dependency files, and setup instructions.

The environment directory contains generated, machine-specific material. Tracking it makes the repository larger without giving another developer a dependable setup.

Keep application data, source files, and credentials outside .venv. When an environment becomes unusable, you should be able to replace it without losing anything that belongs to the project.

Deactivate or Replace an Environment

To leave an activated environment, run:

deactivate

This changes the current shell’s configuration. It does not uninstall packages or delete the environment.

Before replacing an environment, confirm that your dependency records are current and that no source code or data was accidentally saved inside it.

Then deactivate it, remove only the environment directory, and recreate it using the required interpreter.

If you are changing Python versions, rebuilding the environment gives you a clearer starting point than trying to repair an old directory in place.

Virtual Environment vs Virtual Learning Environment

A virtual learning environment is an educational platform used to deliver courses, assignments, assessments, and learning resources.

A Python virtual environment isolates a project’s Python dependencies.

The terms sound similar, but their functions are different.

For example, a school may use a virtual learning environment to distribute programming lessons. Students completing those lessons may create a Python virtual environment on their computers to install the required libraries.

Understanding this distinction helps you find the right instructions and prevents confusion between educational software and development tooling.

Frequently Asked Questions

Do I need to install venv separately?

The venv module is part of Python’s standard library. Some operating-system distributions package supporting components separately, so follow your distribution’s instructions if environment creation reports missing support.

Can I use one environment for several projects?

Yes, but those projects will share installed packages and version constraints. Separate environments usually make independently maintained projects easier to manage.

Must I activate the environment every time?

Only when you want the current shell to resolve commands through it. You can instead call .venv’s Python executable directly.

Does a virtual environment include my API keys?

It does not automatically manage application secrets. Store and supply credentials through your application’s configuration approach, keeping secrets out of source control.

Is requirements.txt enough to reproduce everything?

It records package installation requirements, but not the complete machine setup. Document the Python version, configuration, external services, and system dependencies your application needs.

Make Environment Checks Part of Your Workflow

Learning how to create virtual environment in Python takes only a few commands. Using one reliably requires attention to the interpreter running your code.

Before installing dependencies, confirm the interpreter. After configuring an editor, check it again. When sharing the project, provide enough information to recreate the setup from scratch.

A dependable workflow is:

Choose Python → create .venv → activate or select it → verify paths → install dependencies → record requirements → test a clean rebuild.

Follow that sequence, and your environment becomes an understandable part of the project rather than a hidden source of failures.

Your next storefront is hours away

Spin up a starter, prompt your agent, and take your first order. Sign up today for one full month of access with no long-term commitment.