PythonIntroduction to PythonPython environment setup
How to create a Python environment?
Question 9 of 13 · Updated
On this page
- 1. What is a Python virtual environment?
- 2. Check whether Python is installed
- 3. Create a project directory
- 4. Create a virtual environment using venv
- 5. Activate the environment
- If PowerShell blocks activation
- 6. Verify that the environment is active
- 7. Install packages inside the environment
- Why use python -m pip instead of just pip?
- 8. Save project dependencies in requirements.txt
- 9. Deactivate the environment
- 10. Use the environment in VS Code or PyCharm
- Visual Studio Code
- PyCharm
- 11. Add the virtual environment to .gitignore
- 12. Create an environment with a specific Python version
- 13. venv vs virtualenv vs Conda
- 14. Common problems and how to fix them
- Problem: python or python3 is not recognised
- Problem: No module named venv or ensurepip is unavailable
- Problem: ModuleNotFoundError after installing a package
- Problem: pip reports an externally managed environment
- Problem: the environment works in the terminal but not in the editor
- Problem: the environment stops working after moving the project
- Problem: a package installation fails
- 15. A complete quick-start example
- Frequently asked questions
- Is a Python virtual environment necessary for every project?
- Does creating a virtual environment install Python on my computer?
- Does activating a virtual environment change the system Python installation?
- Can I use the same virtual environment for multiple projects?
- Should I upload the .venv folder to GitHub?
- Is venv the same as a .env file?
- How do I remove a virtual environment?
- Can I create a virtual environment without activating it?
- Key takeaway
A Python environment is the setup in which a Python project runs. It includes the Python interpreter and the packages and dependencies available to that project. In everyday development, the recommended approach is to create a separate virtual environment for each project so that one project's dependencies do not interfere with another's.
For most projects, Python's built-in venv module is the simplest way to do this. You do not need to install a third-party environment manager just to create a basic virtual environment.
1. What is a Python virtual environment?#
A virtual environment is an isolated Python installation directory associated with a project. It has its own Python executable and package installation location. When the environment is activated, commands such as python and pip resolve to that environment in the current terminal session.
For example, imagine two applications:
- Project A needs Django 4.x.
- Project B needs Django 5.x.
If both projects install packages into the same global Python installation, upgrading Django for one project could break the other. Separate virtual environments allow each project to use its own dependency versions.
A virtual environment helps with dependency isolation and repeatable development. It is not a complete security sandbox: it does not isolate operating-system permissions, processes, network access, or secrets.
2. Check whether Python is installed#
Before creating an environment, install a supported Python 3 release if it is not already available. You can obtain Python from the official downloads page or use a trusted operating-system package manager.
Check the installed version from a terminal:
macOS or Linux
BASHpython3 --version
Windows
POWERSHELLpy --version
You can also check which executable a command resolves to:
BASHwhich python3
On Windows, use:
POWERSHELLwhere python where py
If Python is not installed or the command is not found, install Python first. On some Linux distributions, the venv support package is provided separately from the main interpreter package; consult the distribution's package instructions if environment creation reports that ensurepip or venv is unavailable.
3. Create a project directory#
Create a directory for your application and move into it. For example:
BASHmkdir python-demo cd python-demo
A project-local environment is commonly named .venv. The leading dot makes the directory hidden in many Unix-like file browsers and shells, and the name is widely recognised by editors and development tools.
4. Create a virtual environment using venv#
The venv module is included in Python's standard library. Run the command from your project directory.
macOS and Linux
BASHpython3 -m venv .venv
Windows
POWERSHELLpy -3 -m venv .venv
This creates a .venv directory containing the environment's Python executable, supporting files, configuration, and a location for installed packages. The environment is based on the Python interpreter used to run the command. For example, if you invoke python3.12 -m venv .venv, the new environment uses that Python 3.12 installation.
A simplified project layout looks like this:
python-demo/
├── .venv/
│ ├── bin/ # macOS/Linux executables
│ ├── lib/ # environment packages on macOS/Linux
│ └── pyvenv.cfg
├── app.py
└── requirements.txtOn Windows, the executable and library directories use a different layout, typically including Scripts/ and Lib/. The environment structure is managed by Python; you generally should not edit its internal files manually.
5. Activate the environment#
Creating an environment and activating it are separate steps. Activation adjusts the current shell's environment so that the environment's Python and package tools are found first on PATH.
macOS and Linux — bash or zsh
BASHsource .venv/bin/activate
Windows — PowerShell
POWERSHELL.\.venv\Scripts\Activate.ps1
Windows — Command Prompt (cmd.exe)
BAT.venv\Scripts\activate.bat
After activation, your terminal prompt commonly displays (.venv) or the environment name. This is a helpful visual indicator, but verify the interpreter path rather than relying only on the prompt.
If PowerShell blocks activation#
Some Windows PowerShell configurations restrict running scripts. If activation is blocked, you can either use Command Prompt and run the .bat activation script, or follow Microsoft's guidance for an appropriate PowerShell execution policy for your machine. Do not weaken a system-wide security policy just to activate a Python environment.
You can also avoid activation entirely by invoking the environment's interpreter directly:
POWERSHELL.\.venv\Scripts\python.exe --version
On macOS/Linux:
BASH.venv/bin/python --version
Activation is a convenience, not a requirement.
6. Verify that the environment is active#
Run:
BASHpython --version python -c "import sys; print(sys.executable)"
The executable path should point inside your project's .venv directory. You can check this programmatically as well:
PYTHONimport sys print("Python executable:", sys.executable) print("Environment prefix:", sys.prefix) print("Base Python prefix:", sys.base_prefix) print("Running in a virtual environment:", sys.prefix != sys.base_prefix)
When this code runs in a standard venv environment, sys.prefix points to the environment and differs from sys.base_prefix, which points to the base Python installation.
7. Install packages inside the environment#
With the environment active, use python -m pip to install packages:
BASHpython -m pip install --upgrade pip python -m pip install requests
For example, test the installation:
PYTHONimport requests response = requests.get("https://httpbin.org/get", timeout=10) print(response.status_code)
The exact response depends on network availability and the remote service. The important point is that the package is installed into the active environment, not into every Python installation on the computer.
Why use python -m pip instead of just pip?#
A computer can have several Python installations and several pip commands. Running pip install may target a different interpreter from the one used to run your application. Running:
BASHpython -m pip install requests
asks the currently selected python interpreter to run its associated pip module. This reduces the chance of installing a package into the wrong environment.
Check which packages are installed with:
BASHpython -m pip list python -m pip show requests
8. Save project dependencies in requirements.txt#
A project should document the packages it needs so another developer or deployment environment can install them.
After installing the packages required by your project, you can record the environment's installed package versions with:
BASHpython -m pip freeze > requirements.txt
A generated file might look like:
requests==2.x.x
urllib3==2.x.x
certifi==202x.x.xThe versions above are illustrative, not recommended version pins. Your actual file will contain the versions installed in your environment.
On another machine, create and activate a fresh virtual environment, then install the listed dependencies:
BASHpython -m pip install -r requirements.txt
pip freeze records installed distributions and their versions; it is a useful snapshot for many small projects. For more complex applications, teams may use a dedicated dependency-management and lockfile workflow to record direct dependencies, resolve transitive dependencies, and support reproducible builds. A requirements.txt file should be maintained and reviewed rather than treated as a substitute for dependency updates and security checks.
9. Deactivate the environment#
When you finish working in the environment, run:
BASHdeactivate
This returns the current terminal session to its previous Python command resolution. It does not delete the environment or uninstall its packages.
When you open a new terminal, the environment is normally inactive. Activate the existing environment again; do not recreate it every time.
10. Use the environment in VS Code or PyCharm#
Creating an environment in the terminal is only part of the setup. Your code editor must also use the same interpreter.
Visual Studio Code#
- Open the project folder in Visual Studio Code.
- Make sure the Python extension is installed.
- Open the Command Palette.
- Choose Python: Select Interpreter.
- Select the interpreter located inside the project's
.venvdirectory. - Open a new integrated terminal and confirm that the correct environment is active.
If .venv is not listed, use the option to enter or browse to the interpreter path. Typical paths are .venv/bin/python on macOS/Linux and .venv\Scripts\python.exe on Windows.
PyCharm#
Open the project's Python interpreter settings and select the existing interpreter inside .venv, or use the project setup workflow to create a virtual environment. The exact menu names can vary by PyCharm version.
The key rule for any editor is the same: the interpreter selected by the editor, test runner, debugger, and terminal should be the one belonging to the project environment.
11. Add the virtual environment to .gitignore#
Do not normally commit the .venv directory to Git. It contains generated interpreter files and installed packages, can be large, and is specific to the local machine and Python installation.
Add this entry to the project's .gitignore file:
GITIGNORE.venv/ __pycache__/ *.py[cod]
Commit your source code and dependency specification, not the local virtual environment. Other developers can recreate their own environment from the dependency file.
A .env file is different: it commonly stores environment variables such as development configuration or credentials. It is not a Python virtual environment. If it contains secrets, keep it out of version control too, and provide a safe .env.example containing placeholder values when useful.
12. Create an environment with a specific Python version#
A virtual environment uses the interpreter that runs the venv command. It does not, by itself, download or install an arbitrary Python version.
If multiple Python versions are installed, choose the required executable when creating the environment. For example, on a system where Python 3.12 is installed and available as python3.12:
BASHpython3.12 -m venv .venv
On Windows, the Python launcher can select an installed version:
POWERSHELLpy -3.12 -m venv .venv
Check which versions are available using the relevant interpreter launcher or installation manager. If the requested version is not installed, install it first using a trusted distribution or a version manager. Tools such as pyenv can help manage multiple Python versions on macOS/Linux; Conda can manage environments and packages, particularly in data-science workflows.
13. venv vs virtualenv vs Conda#
| Tool | What it does | When to consider it |
|---|---|---|
venv | Standard-library tool for creating lightweight Python virtual environments | Best default for most application projects |
virtualenv | Third-party tool with additional environment-creation features and broader historical compatibility | When a project or workflow needs its specific features |
| Conda | Environment and package manager that can manage Python versions and non-Python dependencies too | Data science, scientific computing, or projects with compiled system-level dependencies |
pyenv | Helps install and select among multiple Python interpreter versions; it is not itself the project's package-isolation environment | When you need to manage several Python versions; commonly paired with venv |
Do not install all these tools just because they exist. Start with venv unless your project's requirements call for another tool.
14. Common problems and how to fix them#
Problem: python or python3 is not recognised#
Python may not be installed, or its executable may not be on PATH. Install Python using a trusted method, open a new terminal, and check the version again. On Windows, try the py launcher if it is installed.
Problem: No module named venv or ensurepip is unavailable#
Some Linux distributions split virtual-environment support into a separate operating-system package. Install the matching venv package for the Python version and distribution, then retry. Avoid copying a venv directory from another machine as a workaround.
Problem: ModuleNotFoundError after installing a package#
The package may have been installed into a different interpreter. Activate the project's environment, verify sys.executable, and install with python -m pip install package-name using that interpreter.
Problem: pip reports an externally managed environment#
Some operating-system Python installations are marked as externally managed, following the approach described in PEP 668. This is intended to prevent pip from changing packages managed by the operating system. Create and activate a virtual environment, then install packages there. Do not routinely bypass the protection with --break-system-packages.
Problem: the environment works in the terminal but not in the editor#
The editor may be using a different interpreter. Select the .venv interpreter in the editor's Python settings and verify the interpreter used by its terminal, debugger, and test runner.
Problem: the environment stops working after moving the project#
Virtual environments are generally not portable because their configuration and executable paths can refer to their original location and base Python installation. Recreate the environment at the new location and reinstall dependencies from the project's dependency file.
Problem: a package installation fails#
Check that the package supports your Python version and operating system, that the environment is active, and that the package name is correct. Some packages require system libraries or build tools. Read the package's official installation instructions rather than installing random binaries or running untrusted installation scripts.
15. A complete quick-start example#
Here is the entire workflow for a new project.
macOS/Linux
BASHmkdir weather-app cd weather-app python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install requests python -m pip freeze > requirements.txt python -c "import sys; print(sys.executable)" deactivate
Windows PowerShell
POWERSHELLmkdir weather-app cd weather-app py -3 -m venv .venv .\.venv\Scripts\Activate.ps1 python -m pip install --upgrade pip python -m pip install requests python -m pip freeze > requirements.txt python -c "import sys; print(sys.executable)" deactivate
After this, the project has its own environment and a dependency snapshot. The next time you work on it, open the project directory and activate the existing .venv again.
Frequently asked questions#
Is a Python virtual environment necessary for every project?#
It is strongly recommended for most projects, especially when installing third-party packages. A simple script using only the standard library can run without one, but project-specific environments help avoid dependency conflicts as the project grows.
Does creating a virtual environment install Python on my computer?#
No. venv creates an environment based on an existing Python interpreter. You must install the required Python version first.
Does activating a virtual environment change the system Python installation?#
No. Activation changes command resolution and environment variables in the current shell. Packages installed through that environment's python -m pip go into the environment rather than the global interpreter's package directory.
Can I use the same virtual environment for multiple projects?#
You technically can, but it is usually better to create one environment per project. Separate environments prevent unrelated projects from sharing dependency upgrades and conflicting package requirements.
Should I upload the .venv folder to GitHub?#
Normally, no. Add .venv/ to .gitignore and commit your source code plus dependency specification. Each developer or deployment system should recreate the environment.
Is venv the same as a .env file?#
No. .venv is commonly the directory containing a Python virtual environment. .env is commonly a text file containing environment-variable settings. They serve different purposes.
How do I remove a virtual environment?#
Deactivate it first if it is active, then delete the .venv directory using your file manager or operating-system command. This removes that environment's installed packages; it does not uninstall the base Python interpreter or delete your project source files.
Can I create a virtual environment without activating it?#
Yes. Run its Python executable directly, for example .venv/bin/python on macOS/Linux or .venv\Scripts\python.exe on Windows. Activation simply makes using the environment more convenient.
Key takeaway#
For most Python projects, create a project directory, run python3 -m venv .venv (or py -3 -m venv .venv on Windows), activate the environment, and install dependencies using python -m pip. Verify that your editor uses the same interpreter, record dependencies, and exclude .venv/ from Git. This gives each project a clean, manageable Python setup without changing the system-wide installation.
References
- 1.
- 2.Python Tutorial — Virtual Environments and Packagesdocs.python.org
- 3.
- 4.Python Packaging User Guide — Installing Packagespackaging.python.org
- 5.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design