Managing multiple Python projects often leads to dependency conflicts due to differing package versions or Python interpreter requirements. Virtual environments solve this by isolating project-specific dependencies.
Begin by installing virtualenv:
pip install virtualenv
Create a basic virtual environment:
virtualenv my_project_env
To specify a particular Python interpreter:
virtualenv -p C:\Python39\python.exe my_project_env
Activate the environment:
my_project_env\Scripts\activate
Deactivate it when done:
deactivate
For enhanced workflow management, install virtualenvwrapper-win:
pip install virtualenvwrapper-win
By default, environments are stored in C:\Users\<username>\Envs. Customize this path by setting the WORKON_HOME system environment variable to your preferred directory.
Create and automatically activate a new environment:
mkvirtualenv my_project_env
List all available environments:
lsvirtualenv
Switch to an existing environment:
workon my_project_env
Navigate into the environment’s root directory:
cdvirtualenv
Access the site-packages folder directly:
cdsitepackages
List enstalled packages in site-packages:
lssitepackages
Remove an environment entirely:
rmvirtualenv my_project_env
To replicate an environment elsewhere, first export its dependencies:
pip freeze > requirements.txt
Then recreate it on another system:
pip install -r requirements.txt