What is venv?
Venv is one of Python’s standard libraries that can be used to create virtual environments, providing separate package or module environments. It allows you to manage different versions of packages for each project in isolated environments.
Advantages of venv
- Isolated Environment: Allows you to work on various projects without conflicts between different packages or Python versions.
- Version Management: Easily manage the necessary packages and their versions for each project.
- Dependency Issues Resolution: Clear understanding of each project’s dependencies minimizes problems during deployment or collaboration.
Disadvantages of venv
- Additional Space: Each virtual environment duplicates packages, requiring extra disk space.
- Management: Managing multiple virtual environments can become complex.
How to Use venv
- Creating a Virtual Environment
Windows:python -m venv [virtual_environment_name]
Linux/Mac:python3 -m venv [virtual_environment_name]
- Activating the Virtual Environment
Windows:[virtual_environment_name]\Scripts\activate
Linux/Mac: source[virtual_environment_name]/bin/activate
- Deactivating the Virtual Environment
All operating systems:deactivate
- Installing Packages
In the activated virtual environment,
use thepip install [package_name]
command to install packages. - Using requirements.txt to Install Packages
To install all packages listed in requirements.txt at once,
use thepip install -r requirements.txt
command. - Checking the Package List
Check the package list in the virtual environment:pip freeze
- Creating requirements.txt in the Virtual Environment
pip freeze > requirements.txt
- Deleting a Virtual Environment
Since a virtual environment is stored as a folder, deleting the folder will also delete the virtual environment.
Example Usage
Creating and Activating a Virtual Environment
# Windowspython -m venv myenv myenv\Scripts\activate
# Linux/Macpython3 -m venv myenv source myenv/bin/activate
Installing and Checking Packages
pip install requests
pip freeze
Exiting the Virtual Environment
deactivate
Additional Tip
Solving Virtual Environment Activation Issues in PowerShell
# Windows
myenv\Scripts\activate.ps1
When virtual environment activation fails due to a security error
+ .\Scripts\Activate.ps1 + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess
If the above message appears and you cannot enter the virtual environment, it means the Windows execution policy is blocked.
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine
By entering the above command in the cmd window, you can confirm that the virtual environment is activated.