Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Saturday, 23 August 2025

How to use Virtual Environments in Python

In this article, I am going to show you how to use Python Virtual Environment (venv). A virtual environment is an isolated workspace for a Python project. Imagine you are working on multiple projects, and each project requires different versions of libraries. You don’t want to mess up your global Python installation. In this scenario, a Python Virtual Environment is a game changer for developers. With a virtual environment, each project can have its own dependencies and can easily run alongside other projects with different requirements on the same machine.

Let’s see how to set up a virtual environment in a Python project. For demonstration, I already opened a folder (Python project) in VS Code. Open the terminal and execute the command below:
The command “python -m venv myproj” creates a new virtual environment named myproj. The venv module is a built-in Python module. After executing this command, Python creates a new folder called myproj. Inside it, you will find a copy of the Python interpreter, a Scripts folder, and Lib/site-packages, which contains the dependencies.
Now, let’s activate the virtual environment using the PowerShell script .\myproj\Scripts\Activate. When you activate a venv, it modifies your PATH and sets an environment variable (Virtual_Env)

In case you encounter the error “Activate.ps1 cannot be loaded because running scripts is disabled on this system”, it occurs because Windows sets PowerShell to Restricted by default, which prevents running any custom scripts.
To fix this issue, you have two options:
1. Temporary: This applies only to the current PowerShell session.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
2. Permanent: If you want to avoid running the above command every time, execute the following command instead. RemoteSigned means local scripts run without restrictions.
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
Once the virtual environment is activated successfully, you will see (myproj) in the terminal.
Let’s install a few libraries or dependencies in the virtual environment. For demonstration, I am installing the FastAPI framework in myproj virtual environment.
To exit the virtual environment, execute the deactivate command. The deactivate command resets your original PATH variable, removes the (myproj) prefix from the terminal, and returns you to system/global Python.

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook