Setting up Virtual Environments in Python

Opeyemi Osakuade
3 min readJan 8, 2021

--

We often neglect some software engineering principles thereby causing conflicts and spending more unnecessary time resolving these conflicts.

One of the neglected principles is using virtual environments.

The main purpose of virtual environments is to create and manage isolated environments for your Python projects. This means each project can have its own dependencies, regardless of what dependencies every other project has

Why Virtual Environment?

Virtual Environments let you deal with the dependencies that your code has with external Python libraries. It avoids having conflicts when your projects depend on different versions of the same library.

Virtual Environments makes it easier to track packages

How do I set this up?

For this article, I am going to be using a recent version of Python (Python 3.7.6) and Visual Studio Code, You can use PyCharm or any IDE you prefer.

  1. To create a new project in Python, it's always best to place it in a folder by itself. Create a new folder called project,

2. Go to command prompt (Windows), Navigate to the project folder, cd Desktop/project

3. Install Virtual Environment by typing pip install virtualenv and Enter

4. Now create a virtualenv named app_env, you can name it anything. This creates a folder or subdirectory named app_env, which will contain all the packages and requirements of a project.

5. The next step is to activate the virtual environment. Type app_env\Scripts\activate. This ensures that all the packages and requirements of the project will be installed in the app_env folder.

You can also deactivate the environment by app_env\Scripts\deactivate

Install the required packages, an example is numpy

To get a complete list of packages and dependencies used in this project, use the command pip freeze > requirements.txt, this creates a requirements.txt file having all dependencies and packages used in the project.

What if I want to install a requirements.txt file I already have into a virtual environment?

  • cd to the directory where requirements.txt is located (refer to point 2)
  • activate your virtualenv(refer to point 5).
  • run: pip install -r requirements.txt.
  • You are good to go!!

4. To create a python file .py in the environment to continue your project. Open project folder in VScode , create a new subdirectory, project_name where your project will be placed.

Inside this subdirectory, create a python file. Once you do this, the python extension will activate and will automatically attempt to detect an existing virtual environment inside that directory.

You are now ready to start using the virtual environment for your project.

--

--