Python

How to Set Up a Python Virtual Environment (venv) on Mac, Windows, or Linux

When working on Python projects, it’s best practice to use a virtual environment. This helps you manage dependencies for each project separately, preventing confilicts and making your development workflow cleaner. In this guide, you’ll learn how to create and activate a Python virtual environment on macOS, Windows, and Linux.

What is a Virtual Environment?

A virtual environment is an isolated Python environment that has its own installation directories and dependencies. With venv, Python’s built-in module (since Python 3.3), you can easily create and manage these environments.

1. Check Your Python Version

First, make sure you have Python 3.3 or higher installed.

python3 --version

If you see a version number (e.g., Python 3.12.4), you’re ready to go!

2. Create a Virtual Environment

Navigate to your project directory:

cd path/to/your/project

Then, create a new virtual environment called venv (or any name you prefer):

python3 -m venv venv

3. Activate the Virtual Environment

MacOS and Linux:

source venv/bin/activate

Windows(CMD)

venv\Scripts\activate

Windows(PowerShell)

venv\Scripts\Activate.ps1

4. Install Packages Inside the Virtual Environment

Once activated, install your dependencies using pip:

pip install <package-name>

All packages will be installed inside your virtual environment, not globally.

5. Deactivate the Virtual Environment

When you’re done working, you can deactivate the environment.

deactivate

Your terminal will return to normal, and you’ll be back to the global Python environment.

6. If you are using Git, Add venv to .gitignore.

venv/

If you found this guide helpful, feel free to share or leave a comment below.

Leave a Reply

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