Creating A Virtual Python Environment (Python)

Non-Virtual Environment Python

One of the issues I’ve hit when using Python is that sometimes a certain version of a Python module/library is needed and conflicts can arise. So if you are like me and fire up PIP to play with modules/libraries you probably have lots of them installed in the Global Python install. Using Docker can resolve this issue but for those that don’t want to use Docker there is also the option of using a Python Virtual Environment.

To create a Python Virtual Environment:

  • Open Terminal / BASH
  • Create a folder for your project (mkdir folder_name)
  • Navigate to the project folder (cd folder_name)
  • Create the virtual environment (python3 -m venv ./venv)
  • Activate the virtual environment (source ./venv/bin/activate)
Terminal commands to create Python Virtual Environment
It only takes a few commands to create a virtual environment

As the above screen shot shows, it only takes a few commands to create and activate the virtual environment. The ls command is just to show that the folder was empty and the final line (with the venv prefix) shows that the virtual environment is activated.

There are a few commands that can be used to double check that a virtual environment is now in use:

New Python Virtual Environment
  • which python – displays where Python is running from
  • which pip3 – displays where Pip is running from
  • pip list – displays the modules/libraries installed by pip, in a new virtual environment this should be minimal.

The virtual environment can be turned off using the deactivate command.

The below shows my regular Python environment, which compared to my new Python virtual environment is packed with modules/libraries.

Non-Virtual Environment Python

3 thoughts on “Creating A Virtual Python Environment (Python)

Comments are closed.