Virtual Environment in Python
A Virtual Environment in Python is an isolated environment that allows you to install and manage project-specific packages without affecting the global Python installation.
Why Use Virtual Environment?
- Avoids package version conflicts
- Keeps project dependencies isolated
- Makes projects portable and reproducible
- Best practice for automation and development
Problem Without Virtual Environment
Suppose one project needs selenium 3 and another needs selenium 4. Installing both globally will cause conflicts.
Types of Virtual Environments in Python
- venv (Built-in module)
- virtualenv (Third-party)
- conda (Anaconda)
Create Virtual Environment Using venv
Step 1: Check Python Version
python --version
Step 2: Create Virtual Environment
python -m venv myenv
This will create a folder named myenv.
Activate Virtual Environment
Windows
myenv\Scripts\activate
Linux / Mac
source myenv/bin/activate
After activation, the environment name appears in the terminal.
Deactivate Virtual Environment
deactivate
Installing Packages Inside Virtual Environment
pip install selenium
pip install requests
Packages installed inside the virtual environment are available only to that environment.
List Installed Packages
pip list
Freeze Dependencies (requirements.txt)
Used to share exact package versions with others.
pip freeze > requirements.txt
Install from requirements.txt
pip install -r requirements.txt
Virtual Environment in Automation Testing
automation_project/
│
├── venv/
├── tests/
├── pages/
├── utils/
├── requirements.txt
└── README.md
Common packages:
- selenium
- robotframework
- requests
- pytest
Common Mistakes
- Forgetting to activate virtual environment
- Installing packages globally by mistake
- Not sharing requirements.txt
Best Practices
- Create one virtual environment per project
- Never commit venv folder to Git
- Always use requirements.txt
- Use meaningful environment names
Common Interview Questions
- What is a virtual environment?
- Why do we need virtual environments?
- Difference between venv and virtualenv?
- What is requirements.txt?
Conclusion
Using a virtual environment is a best practice in Python development and automation testing. It keeps dependencies clean, isolated, and manageable across projects.
👉 Learn more Python and Automation tutorials on way2testing.com
No comments:
Post a Comment