Original Conceptual Python Workspace Showing Terminal Commands And Isolated Project Dependencies

How To Create Python Virtual Environment

Learn how to create Python virtual environment with venv on Windows, PowerShell, Command Prompt, macOS and Linux, then install packages safely.

Quick Answer

Create a Python virtual environment from your project directory with python -m venv .venv, or py -m venv .venv on supported Windows installations. Activate it using the correct shell script, or run the environment’s Python executable directly. Verify the interpreter before installing packages.

This hands-on tutorial provides Windows, macOS and Linux examples, package installation guidance, verification and safe troubleshooting for common errors.

What A Python Virtual Environment Does

A Python virtual environment is an isolated directory-based environment containing a Python interpreter configuration and its own location for installed Python packages. It lets one project use a package version without automatically changing the package environment used by unrelated projects or the operating system. Python’s built-in venv module is a standard way to create such environments.

For example, one project might need a particular version of a web framework, while another project requires a newer release. Placing each project’s dependencies in its own virtual environment reduces accidental conflicts. The environment is not a security sandbox that protects the operating system from malicious code; packages you run can still access resources allowed by your user account.

The official Python venv documentation explains environment creation, configuration files and platform-specific activation. The Python Packaging User Guide demonstrates using venv with pip to manage project packages. Those are better references than copying installation commands from an unrelated project.

An environment typically contains a pyvenv.cfg configuration file and a Scripts directory on Windows or a bin directory on Unix-like systems. The environment uses the Python version selected when it is created. Creating a virtual environment does not download a new arbitrary Python version unless another tool explicitly handles interpreter installation.

Our Python installation guide for Windows covers the prerequisite interpreter. This article focuses on creating, activating and validating a per-project environment while maintaining safe dependency habits.

Check Python Before Creating The Environment

Before running a virtual-environment command, confirm that Python is installed and that the terminal launches the interpreter you intend to use. On Windows, py --version can report the selected Python launcher version on systems where that launcher is available. python --version may work as well. On macOS or Linux, python3 --version is common.

A version result confirms which interpreter the terminal found; it does not establish that all other Python versions are absent. A developer machine may have several interpreters installed through a system package manager, a distribution, a development environment or an organization-managed tool. The version used for venv depends on the command invoked.

If Windows reports that Python is not found, review the installation and launcher configuration before editing environment variables blindly. Some systems use Python installation managers or app execution aliases. Their setup behavior changes over time, so follow the current official instructions for that installation method.

On Debian-like Linux systems, the operating-system package selection may provide python3 but require an additional supported venv component in some configurations. A failure to create a venv can therefore reflect missing distribution support rather than an application coding error.

Use a project folder that you own and can modify. Avoid placing experiments inside Windows system directories or the system Python installation path. A normal user workspace keeps files separated and easier to clean up.

The Python Packaging User Guide explicitly recommends checking Python’s availability before creating an environment. Begin with that observation rather than running installer commands as an administrator without understanding their effect.

Create A Virtual Environment On Windows

Open Windows Terminal, PowerShell or Command Prompt in the intended project directory. If you do not yet have a project folder, create a normal directory under your user-owned workspace and navigate to it. The environment should belong to that project, not to a random system directory that other applications depend on.

Run py -m venv .venv if your Windows Python launcher supports that command. Alternatively, use python -m venv .venv when python refers to the intended interpreter. The -m venv option invokes Python’s environment creation module, and .venv is the new directory name.

Windows Virtual Environment Setup
py --version
py -m venv .venv
.venv\Scripts\activate.bat
python -c "import sys; print(sys.executable)"
python -m pip --version
Original Instructional Example For Command Prompt. PowerShell Uses Activate.ps1 Instead

In this demonstration, the activation line is for Command Prompt. PowerShell uses a different activation script discussed below. You do not need activation merely to create the environment; creation should finish by producing the appropriate directory tree.

Do not overwrite an existing .venv directory casually. It may contain packages and configuration for another local setup. If one already exists, inspect it, preserve necessary dependency records and decide whether to reuse or deliberately recreate it.

The official venv reference documents the Windows Scripts directory and built-in creation command. It also explains that activation changes the shell’s environment rather than creating the virtual environment itself.

After creation, verify the intended interpreter and packages before starting a real project. A directory appearing in File Explorer is not sufficient proof that the terminal is using it.

Activate Python Venv In PowerShell

After creating .venv, PowerShell can activate the environment with .\.venv\Scripts\Activate.ps1. When activation succeeds, the prompt may show an environment name and the shell’s PATH resolves python and other installed commands from that virtual environment first. Prompt appearance is convenient but should not be your only verification.

On some Windows systems, PowerShell execution policy prevents the activation script from running. Python’s venv documentation notes this possibility. It does not mean Python itself is broken or that you must permanently weaken system-wide security policy to use virtual environments.

A safer alternative is to call the virtual environment’s interpreter directly, for example .\.venv\Scripts\python.exe -m pip --version. You can run Python scripts through that explicit interpreter path without activating the shell. This avoids a need to change execution policy for routine project work.

If your organization approves a user-scope policy adjustment for signed or local scripts, follow its documented procedure and assess the security implications. Do not copy commands that disable execution policy globally from an unfamiliar forum. Managed computers may enforce policy deliberately.

After activation, inspect python -c "import sys; print(sys.executable)". The executable path should point into the intended project environment. If it still points to a global installation, activation did not take effect for that terminal or another path takes precedence.

Activation affects the current shell session. Closing that session or running deactivate typically removes the environment’s activation from the shell; it does not delete installed packages.

Our command-line guide explains terminal working directories and commands for beginners who are unfamiliar with shell-specific syntax.

Activate Python Venv In Command Prompt

Windows Command Prompt uses a batch activation script rather than PowerShell’s .ps1 file. In the project directory, the common command is .venv\Scripts\activate.bat. The activation script adjusts the current command environment so that python and other relevant executables generally resolve to the virtual environment.

A Command Prompt session and a PowerShell session have different scripting languages, so commands copied between them may fail. If a guide shows source .venv/bin/activate, it is generally describing a Unix-compatible shell, not standard Windows Command Prompt.

To confirm that activation selected the correct environment, run python --version and python -c "import sys; print(sys.executable)". The second command should report a path inside the .venv directory. If your shell reports that the activation script is missing, check the project path and confirm the environment was created successfully.

You can also avoid activation by using .venv\Scripts\python.exe explicitly. This is particularly useful for scripts, scheduled tasks and environments where the current terminal’s PATH might be modified by another tool.

The location of environment packages is not the same as the directory containing your project source files. Most developers keep .venv next to their application files while ignoring the environment directory in Git. This layout is conventional, not a hard requirement.

Do not run ordinary project package installation commands from an elevated Administrator Prompt unless the specific procedure requires it. A properly configured user-owned virtual environment typically does not require administrator privileges.

Create Venv On macOS Or Linux

On many macOS and Linux installations, the appropriate command is python3 -m venv .venv from the project directory. The environment normally places its executable scripts under .venv/bin. After creation, a POSIX-style shell such as Bash or zsh can activate it with source .venv/bin/activate or the supported dot-command equivalent.

macOS And Linux Virtual Environment Setup
python3 --version
python3 -m venv .venv
source .venv/bin/activate
python -c "import sys; print(sys.executable)"
python -m pip --version
Original POSIX Shell Example. Fish And Other Shells Have Different Activation Scripts

Not every operating system configures Python in the same way. A system-installed interpreter may use distribution packages, while another installation comes from a dedicated Python manager. If the venv module is unavailable, consult that distributor’s supported instructions rather than trying random installer scripts.

The Python reference documents the bin directory and activation scripts. The Packaging User Guide explains how to verify that the correct interpreter is active.

The literal shell command source is not universally supported in Windows shells. Conversely, the Windows Scripts path is not the ordinary path for a macOS virtual environment.

You can skip activation by invoking .venv/bin/python directly. This can be useful when a script or development tool needs one explicit interpreter without relying on interactive shell state.

Verify The Environment Is Actually Active

Creating an environment and using it are distinct stages. A developer can successfully create .venv and then accidentally install packages with a different Python interpreter. This usually happens when the terminal was not activated, an editor selected another interpreter, or several Python installations are available.

Run python -c "import sys; print(sys.executable)" in the intended environment. The path should refer to the environment’s executable. Run python -m pip --version to inspect which pip instance corresponds to that interpreter. These checks are more reliable than only looking for a changed prompt.

A separate python -c "import sys; print(sys.prefix); print(sys.base_prefix)" can reveal the virtual-environment context. In a typical venv, sys.prefix points to the environment while sys.base_prefix points to the base installation. The interpreter’s behavior and reporting should be interpreted under the supported Python version.

CheckExpected ObservationProblem If Different
sys.executablePath Inside .venvWrong Interpreter
python -m pip –versionpip Associated With Current PythonWrong Package Target
sys.prefixEnvironment DirectoryEnvironment Not In Use
Project DependenciesPackages Installed In VenvMissing Installation Or Wrong Environment

An editor such as VS Code may need to select the project interpreter separately. A terminal that is activated correctly does not guarantee that every integrated tool automatically adopts the same path.

If the environment is wrong, fix the interpreter selection before installing or deleting packages. Repeated pip commands directed at a global Python can create a larger problem than the original missing dependency.

Install Packages With The Correct Pip

Inside an activated environment, use python -m pip install package-name for a package from an approved source. The python -m pip form makes the intended interpreter explicit and reduces ambiguity when more than one pip executable exists. Replace package-name with a real verified distribution package identifier.

The Python Packaging User Guide describes installing with pip in a virtual environment. A package installation can run build steps or other code under your user account, so use trusted publishers and inspect dependencies for sensitive projects.

A safe beginner exercise is to inspect pip’s version and list existing packages before installing anything. Then choose one legitimate package required by your project, check its source and install only within the project environment. Verify functionality by importing or running the package according to its documented interface.

Avoid sudo pip install as a generic fix on macOS or Linux. Administrator installation can alter system-managed files and cause dependency conflicts. A user-owned virtual environment usually avoids the need for elevated permission.

A Python distribution name does not always match its import name. A project may be installed under one identifier but imported under another. Follow the package’s official usage documentation instead of concluding the installation failed solely because a guessed import name does not work.

Our package manager overview explains dependency resolution and software sources. Pip is one ecosystem’s package manager, not a replacement for every operating system package operation.

Use Requirements Files For Reproducibility

A project often needs several packages with particular version constraints. A requirements file can record distribution names and version specifiers for pip. A commonly used file is named requirements.txt, though the name is a convention rather than a Python language requirement.

To install listed packages into the currently selected environment, the typical command is python -m pip install -r requirements.txt. Review the file first because it may reference direct URLs, local paths, editable installs or other package sources. Do not blindly execute an untrusted project’s dependency file.

The pip user guide documents requirements files and supported formats. You may see python -m pip freeze used to output installed package versions. That command captures the current installed distribution set, which can be useful for records but does not by itself explain which packages are direct requirements or certify reproducible builds.

Not every project should automatically commit a raw freeze output as its only dependency policy. Some workflows use curated requirements, lockfiles or tools that resolve transitive dependencies explicitly. The right choice depends on project scale and packaging needs.

A requirements file may contain platform-specific packages that cannot be installed identically on all operating systems. Python-version markers and binary compatibility matter too. Test restoration of the environment on a supported target platform rather than assuming a list of names guarantees portability.

For software distribution concepts, see the software repository guide. The file describes dependencies; a repository publishes the package artifacts that pip will retrieve.

Do Not Commit The .venv Directory To Git

Virtual environment directories contain installed packages, scripts and interpreter-specific configuration that are generally tied to the environment where they were created. Committing these files directly to source control can inflate repository size, introduce platform-specific binaries and produce confusing differences across developers’ computers.

Most projects add the .venv directory to their .gitignore rules. The project then stores source files and the appropriate dependency declarations while each developer creates an independent environment. This keeps version control focused on meaningful project content rather than a large automatically generated package tree.

A typical ignore rule is simply .venv/. Check that your project’s existing ignore file does not use a conflicting convention. An ignore rule affects untracked files; it does not automatically remove a virtual environment already committed into repository history.

Our Git Add Vs Git Commit guide explains the staging process and why untracked files need deliberate handling. If a repository accidentally contains secrets or installed artifacts, deleting them in the working directory may not remove them from earlier commits.

The Python venv documentation notes that virtual environments are generally not considered movable or copyable. Their scripts may contain absolute paths to the interpreter, so recreate the environment after moving the project rather than assuming the directory can be copied unchanged.

A clean repository plus a documented environment-creation command is easier to review, share and rebuild. Portability comes from dependency records and tested setup steps, not from committing machine-specific interpreter folders.

Deactivate, Delete And Recreate A Venv Safely

To leave an activated virtual environment in a typical shell, run deactivate. This restores relevant shell settings affected by activation; it does not uninstall packages or delete the .venv directory. You can activate the same environment again in a later terminal session.

To remove a disposable environment, close applications that are using it and delete the specific .venv directory through your normal file manager or a carefully targeted command. Before doing so, confirm that the directory is the intended one and that its packages can be recreated. Do not delete the project source folder or a shared system interpreter.

Recreating an environment is often appropriate after a Python version upgrade, moving a project to another machine or resolving an irreparably confused dependency set. Create the environment with the desired interpreter, activate it or invoke its interpreter directly, and reinstall from a reviewed dependency specification.

A venv is not a backup of the source project or its external database. It is a tool for managing packages and interpreter context. Preserve application data, environment variables and required credentials through separately approved mechanisms.

If deleting the environment would interrupt a running service, use a controlled maintenance procedure. A production deployment should specify interpreter and dependency versions, testing and rollback rather than depending on a single workstation folder.

The safe rule is simple: environment activation is temporary, the directory is replaceable when dependencies are documented, and user data should live outside disposable packaging structures.

Virtual Environment Vs Conda Vs Docker

Python venv isolates installed Python packages and the selected interpreter context within a project directory. Conda and similar environment managers can additionally manage different interpreters and non-Python packages under their own model. Docker containers package an application and more of its runtime environment through operating-system isolation and images.

These tools can coexist. A project might use a venv during local development and a container for production deployment. A scientific workflow might choose a dependency manager with native-library support. The correct choice depends on software requirements rather than a universal ranking.

ToolPrimary PurposeImportant Limit
venvPython Package IsolationNot An OS Security Sandbox
CondaEnvironment And Package ManagementSeparate Ecosystem And Configuration
DockerContainerized Runtime And DeploymentRequires Image And Container Operations

A virtual environment does not prevent untrusted Python code from opening your documents if that code runs with your user account’s permissions. It also does not isolate every shared library or operating-system resource. Security-sensitive execution needs an appropriate broader sandbox and permission model.

For small Python applications, venv is usually an understandable standard starting point. If the project depends on complex native scientific packages, another manager may offer operational benefits. Evaluate ecosystem support, reproducibility and team practices.

The goal is to avoid dependency conflict and make the project repeatable. Choose tools that solve those problems with the least unnecessary complexity.

Fix Common Python Venv Errors

If the terminal says Python is not found, confirm the intended interpreter is installed and discoverable through the supported launcher or PATH. If the venv module is missing on Linux, consult the distribution’s official package instructions. Do not edit protected directories or download arbitrary scripts to solve a basic setup error.

If activation fails in PowerShell, inspect the exact message. A policy preventing the activation script from running does not prevent using the environment’s interpreter directly. Prefer .\.venv\Scripts\python.exe as a low-risk workaround instead of weakening security settings without approval.

If a package installs successfully but cannot be imported, compare sys.executable and python -m pip --version. An editor or terminal may be using a different interpreter. Also check whether the package’s distribution name differs from the import name specified in its documentation.

An externally managed environment warning on some Linux systems often means the operating system protects its system Python from direct package-manager modification. Creating a user-owned virtual environment is generally preferable to overriding that protection.

A permission error may come from creating .venv inside a protected folder or from a file locked by another process. Move the project to a normal authorized workspace rather than running every command as administrator.

Finally, if a project requires a specific Python version, creating a venv with a different interpreter will not magically satisfy that requirement. Install or select a compatible interpreter through an approved channel, then recreate the environment.

Complete Python Virtual Environment Checklist

Begin with a user-owned project directory and the intended Python version. Create .venv using the platform-appropriate command. Activate it with the matching shell script or invoke the environment’s Python executable directly. Verify both sys.executable and the pip version before installing packages.

Read the project’s dependency specification and confirm its sources. Install using python -m pip in the intended environment, then run a harmless test that imports or executes the required package. Record compatibility expectations and error messages without exposing passwords or tokens.

Add .venv/ to Git ignore rules where appropriate, retain a reviewed dependency declaration and avoid committing secret .env files. When sharing the project, provide instructions that allow another developer to recreate the environment using a compatible Python interpreter.

Test the real application, not only the success of environment creation. An environment can be configured correctly while the application still has configuration, database or API errors. Reproducible setup is an important foundation but not an end-to-end software quality guarantee.

When updates are required, modify dependencies deliberately and test before deployment. If the environment becomes inconsistent, recreate it from trustworthy package specifications rather than manually copying libraries into site-packages.

The complete workflow is create, verify, install, test, document and recreate when necessary. That approach gives beginners an understandable and maintainable Python development setup while keeping operating-system packages and other projects separate.

Frequently Asked Questions

How Do I Create A Python Virtual Environment On Windows?

Run py -m venv .venv or python -m venv .venv from the project directory using the intended Python interpreter.

How Do I Activate Venv In PowerShell?

Use .\.venv\Scripts\Activate.ps1 in an authorized PowerShell session, or invoke the environment’s python.exe directly without activation.

How Do I Activate Venv In Command Prompt?

From the project folder, use .venv\Scripts\activate.bat.

How Do I Activate Venv On macOS Or Linux?

Run source .venv/bin/activate in a supported POSIX-compatible shell.

How Can I Check Whether Venv Is Active?

Inspect sys.executable using python -c and verify that python -m pip points to the expected environment.

Do I Need To Activate A Virtual Environment?

No. You can invoke the environment’s Python interpreter directly using its path.

Should I Commit .venv To Git?

Normally no. Ignore the generated environment and keep source code plus reviewed dependency records.

Is A Python Virtual Environment A Security Sandbox?

No. It isolates Python package installations but does not prevent code from using your normal user permissions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Discover more from XYZ Tech

Subscribe now to keep reading and get access to the full archive.

Continue reading