Virtual environment is a specific folder inside our project directory, used to install all the project specific packages & versions only instead of picking from globally installed packages.
Benefits –
Isolates the project from the global python or python library versions.
Python project can work on your machine, but when you run on other machines, it might not work, there could be different versions of python or python libraries installed, so by making a virtual environment, you have the liberty to install specific version of libraries.
Note – also you can leverage python’s requirements.txt feature to install those specific version of libraries.
Installing virtual env
If you are using python >= 3.3 version [mostly recomended], then venv [virtual environment] comes default, you need not to install the package.
However if you are using python <3.3, then you should install virtualenv
For Mac OS –
python3 -m pip install --user virtualenv
For Windows –
py -m pip install --user virtualenv
Creating virtual environment
Navigate to your project directory & open the command prompt or terminal, type & enter
for Mac OS –
python3 -m venv [venvName]
For windows –
py -m venv [venvName]
If you are using lower version of python ~2.7, then replace venv
to virtualenv
The above command will create a folder with name vencName you provided, where all your project specific libraries will be installed.
Note – You should include this folder into your .gitignore
if you are pushing your code into git remote repo, or even while sharing to some one, that’s why maintaining requirements.txt is recommended so the other person can know what libraries to install for successful run.
Activating venv
We need to activate the virtual environment before installing any packages.
Navigate to project directory in command prompt, and type
for mac os
source venvName/bin/activate
For windows
.\venvName\Scripts\activate
Verify
For mac os
which python
For windows
where python
Installing packages
After activating the virtual environment, you can install the packages by typing
pip install [any Package]
example –
pip install -U selenium
To deactivate virtual env
Just navigate to project directory in command prompt, and type
deactivate
Note – you can create multiple virtual env with different name & deactivate or activate any one based on need.
Hope this helps!
Reference – https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#installing-virtualenv