Saturday, February 21, 2026

Setting up a Python virtual environment


Python virtual environment


Setting up a Python virtual environment (venv) involves creating an isolated folder for your project dependencies and then activating it in your terminal. This prevents conflicts between different projects.

Step 1: Create the Virtual Environment

Navigate to your project directory in the terminal or command prompt and run the following command. It will create a new folder named venv (a common convention) in your current directory.

    bash: python -m venv venv

    python (or python3 on some systems): Invokes the Python interpreter. 
    -m venv: Tells Python to run the venv module as a script.
    venv: The name of the directory to create for the virtual environment

Step 2: Activate the Virtual Environment

After creating the environment, you must activate it. The command depends on your operating system and the shell you are using

    bash : source venv/bin/activate

Once activated, your terminal prompt will usually change to show the name of the environment in parentheses (e.g., (venv)).

Step 3: Install Packages

With the venv active, any packages you install using pip will be placed in the isolated environment's site-packages directory.
bash : pip install <package_name>
You can generate a requirements.txt file to share your project's dependencies:

    bash : pip freeze > requirements.txt

Step 4: Deactivate the Environment

When you are finished working on the project, you can exit the virtual environment by simply typing:

    bash : deactivate