But while we developing complex software projects like building a python library, an API, or software development kit, often you will be working with multiple files, multiple packages, and dependencies. You will need to isolate your Python development environment for that particular project.
Why We Use Virtual Environment. ?
ProjectB require
also the same package Django but different version, let’s say version 1.10, which
has some breaking changes between version 1.0 and 2.0. If you pip install to
global python library the existing version 1.0 will update to 2.0 and when you
run the ProjectA you
may face error.
So what the
above scenario teaching us is isolation of packages will resolve the problem
and that’s exactly what virtual environment is.
We can have
multiple virtual environments with different python versions, and it will be
isolated python, packages, scripts from other virtual environments and your
system.
VirtualEnv And Venv
Installing Virtualenv
Open ‘command prompt’, navigate to your directory using ‘cd’ command. then follow below.
pip install virtualenv
or use below code to install specifically for python 2
py -2 -m pip install virtualenv
To Test your installation.
virtualenv --version
Create a Virtualenv
virtualenv myDirectory
or use below code by mentioning python 2
specifically.
py -2 -m virtualenv myDirectory
After running the command a directory called ‘myDirectory’ will be created with all the necessary executable to use the
packages that a Python 2 project would need.
Activate virtualenv
Navigate to the directory we created for virtualenv using ‘cd’ command.
> cd myDirectory
> Source\activate
(myDirectory)>
After activation, install the required packages using pip install.
Deactivate virtualenv
Just type ‘deactivate’ and exit from the virtualenv.
(myDirectory)> deactivate
Installing Venv
Open ‘command prompt’, navigate to your directory using ‘cd’ command. then follow below.
pip install venv
or use below code to install specifically for python 3.xx
py -3 -m pip install virtualenv
To Test your installation.
venv --version
Create a Venv
venv myDirectory
or use below code by mentioning python 3.xx specifically.
py -3 -m virtualenv myDirectory
After running the command a directory called ‘myDirectory’ will be created with all the necessary executable to use the
packages that a Python 3.xx project would need.Activate Venv
Navigate to the directory we created for virtualenv using ‘cd’ command.
> cd myDirectory
> Source\activate
(myDirectory)>
After activation, install the required packages using pip install.
Deactivate Venv
Just type ‘deactivate’ and exit from the venv.
(myDirectory)> deactivate
Conclusion
Both virtualenv and venv using for same thing but the python version will be different.
AS the python 2 already reached to end of life stage, it is no longer recommended to using
virtualenv. Use venv with python 3 instead.