Setting up Python Virtual Environment for development
Using virtualenv to create different isolated virtual python development environment.
Why to create different isolated environments for different projects bases? ’cause it’s easy to manage and troubleshoot and move-over you will not end up bricking up your current development environment and if you must do so, you can always reset virtual environment for messed up project without disturbing other #stable setups.
How to?
1. Installing virtualenv with pip
If you want to setup virtual environment for specific python version use commands which uses that specific version’s pip :
python3 -m pip install virtualenv
This will install virtualenv for python3, (same can be done for python2 but who uses that now as it’s already past it’s EOL.)
2. Creating Virtual Environment for your project
After installing virtualenv, it’s time to create a new environment for our project let’s call it “ProjectA”
First let’s move to HOME directory if you are using Linux, just to make it easy for later usage.
cd $HOME
Now let’s create a virtual environment with name “ProjecAenv”
python3 -m virtualenv ProjectAenv
where you can change “ProjectAenv” to anything you want.
“-m” option in python means “module”, so here we are using virtualenv module we just installed.
3. Activate your brand-new-shiny virtual environment
To activate your virtualenv you need to activate the script “/bin/activate.bat” in windows and use resource “/bin/activate” in linux :
source ./ProjectAenv/bin/activate
4. Do whatever rocks your boat
Your new environment is active and you can do whatever you want, go install those crazy python libraries without fear !
let’s install numpy in current environment :
5. Deactivate the environment
after all play, we need to deactivate the environment just type the magic word : “deactivate” and that’s it.
BONUS : generate “requirements.txt”
As you are using virtual environment and at some point you want to export your project and want to make those fancy requirements.txt ?
just activate your virtualenv and do this:
python3 -m pip freeze > requirements.txt
this will create the file and as you have only installed the modules for this project only, you will get clean list of your project requirements.
I hope this helped you in one way or other, see you in next article! till then stay caffeinated enough.