Python’s virtualenv is a tool to create isolated Python environments. It helps manage dependencies for different projects, ensuring no conflicts between libraries or versions.
virtualenv allows you to create environments where:
To install virtualenv, use pip:
pip install virtualenv
To verify the installation:
virtualenv --version
Use virtualenv to create a new environment:
virtualenv env_name
virtualenv myenv
virtualenv -p python3.11 myenv
This allows you to use a specific Python version.
To use the environment, activate it.
myenv\Scripts\activate
source myenv/bin/activate
When activated, you’ll see the environment name in your terminal prompt:
(myenv) $
To stop using the environment, deactivate it:
deactivate
This will return you to the system Python environment.
To remove a virtual environment, simply delete its directory:
rm -rf myenv
For easier management of multiple virtual environments, you can use virtualenvwrapper.
Install virtualenvwrapper using pip:
pip install virtualenvwrapper
Add the following to your .bashrc or .zshrc:
export WORKON_HOME=$HOME/.virtualenvs
source $(which virtualenvwrapper.sh)
Reload your shell:
source ~/.bashrc
mkvirtualenv env_name
workon env_name
lsvirtualenv
rmvirtualenv env_name
Use requirements.txt:
Generate a list of installed packages:
pip freeze > requirements.txt
Reinstall the dependencies in another environment:
pip install -r requirements.txt
Project-specific Environments:
Create a virtual environment within your project folder:
cd my_project
virtualenv venv
Add the environment directory (venv) to .gitignore to avoid committing it to version control.
Environment Variables:
.env files to keep sensitive information like API keys.Objective: Learn to create, manage, and utilize virtual environments using virtualenv and virtualenvwrapper.
Install virtualenv:
virtualenv package using pip and verify its installation.pip install virtualenv
virtualenv --version
Create a Virtual Environment:
test_env.requests library.virtualenv test_env
source test_env/bin/activate # On Windows: test_env\Scripts\activate
pip install requests
Use requirements.txt:
requirements.txt file.requirements.txt file to reinstall packages in the new environment.pip freeze > requirements.txt
deactivate
virtualenv new_env
source new_env/bin/activate
pip install -r requirements.txt
Experiment with Python Versions:
virtualenv -p /path/to/python3.9 py39_env
source py39_env/bin/activate
python --version
Explore virtualenvwrapper:
virtualenvwrapper.virtualenvwrapper commands.pip install virtualenvwrapper
export WORKON_HOME=~/Envs
mkdir -p $WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh # Adjust path as necessary
mkvirtualenv wrapper_env
workon wrapper_env
rmvirtualenv wrapper_env
Bonus: Understand Environment Isolation:
flask) in one environment and verifying that it is not available in another.