"venv"- Python Virtual Environment

Gaurab WagleGaurab Wagle
2 min read

It will be a straightforward guide:

A virtual environment is a Python environment such that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) any libraries installed in a “system” Python, i.e., one which is installed as part of your operating system.

eg: You might need a python version of 10.5 for your project then you will install that python version by making a virtual environment. When you use the vir env you will be using 10.5 version but when you are outside of the vir env you will be using the other version(latest) maybe 20.1 ...

Make sure to install the following things:

For Linux:

python3 -m venv myenv
source myenv/bin/activate

"myenv" is the name of the virtual environment folder.
Source is how we activate the vir env we created.

For Windows:

python3 -m venv myenv
myenv\Scripts\activate

The code we put are just the folders inside of the myenv folder. You can check them.

C://User/Gaurab/Desktop : 
(myenv)

Once activated, your terminal prompt will show (myenv) to indicate the virtual environment is active as shown above ^^.

Deactivate:

deactivate

Just type deactivate and you will see the (myenv) disappear and you're out of the virtual environment.

Some tips:
Always activate the virtual environment before installing any packages. This keeps your project’s dependencies isolated.

  • Install packages using pip after activating the environment:

      pip install package-name
    
  • Keep your virtual environment folder out of version control (e.g., add myenv/ to .gitignore).

  • Deactivate the environment when you're done working by running:

      deactivate
    
  • Use requirements.txt to list your project's dependencies:

      pip freeze > requirements.txt
    

    Others can install these dependencies using:

      pip install -r requirements.txt
    
  • Avoid using sudo with pip install inside a virtual environment; it's unnecessary and can cause issues.

0
Subscribe to my newsletter

Read articles from Gaurab Wagle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gaurab Wagle
Gaurab Wagle

CS - KU, Nepal. Exploring my ways as a developer. Available for collaboration on projects