Python Virtual Environments
Problem Statement: I am working on multiple python projects on my machine at a time. Every project requires its own set of packages, sometimes with a specific version.
1. How do I keep track of all packages required for the project and list them in requirements.txt file so that it can be used at the time of deployment on another host.
2. How do I avoid conflicts between projects, say project A require a different version of a package than project B.
Solution: Python Virtual Environments, Each python project should have its own Virtual Environment with its own dependent packages
How to use Python Virtual Environment
Install Virtualenv
pip install virtualenv
Create Virtual Environment
virtualenv env_name
A new directory will be created, which contains necessary python executables.
You can also specify interpreter of your choice.
virtualenv -p c:\program files\python38 env_name
Activate Virtual Environment
env_name\Scripts\activate.bat
As you can see Vitual Environment will have only basic packages at the beginning. But now you can start installing packages as required.
Install packages and prepare Requirements file
Use Pip to intall packages as usually done
prepare requirements.txt
pip freeze > requirements.txt
Now this file can be used while deploying application on any other host.
Deactivate Environment
deactivate
Remove Virtual Environment
Simply delete the virtual environment directory.
rmdir env_name /s