Virtual environments are a helpful tool for developers in development that enable them to keep the resources they require for developing one application separate from and inaccessible by another.
When created, Python virtual environments each come with their own Python binary. These environments can have their own set of installed Python packages and directories.
With the Python virtual environment, you can have packages installed. These will not affect the general Python installation, but will only have an effect on files found in it.
Let’s say you want to build with version 2 of Django in a project A and version 3 in project B. It is possible to just create two virtual environments, each for installing one of the versions.
There are a few ways to do this. I will show you how to use the venv
module to do so.
First, make sure you have the right version of pip
. You can get it here if you don’t have it.
Then, using the pip
command, install the virtualenv
package like so:
pip install virtualenv
python3 -m venv /path/to/new/virtual/environment
The following is the path to the directory where you wish to have your virtual environment directory:
/path/to/new/virtual/environment
If you are on Windows, then there’s no need to indicate the version of Python. Just
Python
is enough.
<venv>\Scripts\activate.bat
<venv>\Scripts\Activate.ps1
$ source <venv>/bin/activate
<venv>
is the name of your virtual environment.
All commands should be used when in the virtual environment folder.
Now let’s create a virtual environment called myenv
on Windows, using the cmd.
python -m venv desktop/myenv
This will create a myenv
virtual environment on my desktop.
I can activate it by changing my directory to desktop on my cmd and entering the command below:
myenv\Scripts\activate.bat
For myenv
, we will do:
deactivate