How to create a virtual environment in Python

What are virtual environments?

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.

How to create a virtual environment in Python

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

  • Now, go to your terminal or command line and execute the following command:

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.


  1. On Windows, you can activate your virtual environment by using the following command on CMD.exe:

<venv>\Scripts\activate.bat

  1. If it is PowerShell, then use:

<venv>\Scripts\Activate.ps1

  1. While on the Bash terminal, you can activate by using:

$ 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.

  • I will start by entering:

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

  • You can easily go back to your original Python environment by deactivating the active virtual environment.

For myenv, we will do:


deactivate

Free Resources