virtualenv is a tool used to create separate workspaces for each of your Python applications. For each of my projects, I begin by creating a new virtual environment. From Python 3 onwards, venv should be one of the included modules. Anything older might require the need to install virtualenv through your package manager.

For instance, if I were to create a new webscraping project, I would want to create its own environment. But before that, iIf I run $ pip freeze | wc -l, you can see that it includes every package included on my machine, listing a total of 116 from whatever I have installed. We’ll compare that to after we’ve created our environment. Creating one takes just one line.

$ python -m venv v-web    # or 
$ virutalenv v-web

Now we’re going to activate our virtual environment. Run $ source [env_name]/bin/activate. Your terminal should now include a short prefix named after your virtual environment.

I’ve also run pip freeze just to show that those 104 are not included in our new environment.

I’ve also run pip freeze just to show that those 104 are not included in our new environment.

Now that we have our isolated environment, we can begin installing the packages necessary. For now, we’ll just install the requestspackage.

While your environment is activated, pip freeze will show you whats installed specific to that environment.

While your environment is activated, pip freeze will show you whats installed specific to that environment.

Curating a list of what the required packages are can help in the future. Run the same pip freeze command; however, this time, pipe it into a text file called requirements.txt.

You’ve now taken the output from pip freeze and thrown it into a requirements list.

You’ve now taken the output from pip freeze and thrown it into a requirements list.

To step out of your environment, you need to deactivate. Run source v-web/bin/deactivate to close your environment. You can now take that list you made earlier and shortcut setting up your project. Use the command pip install -r requirements.txt and it will install all the packages on that list.

Use pip install -r requirements.txt to install the packages in your requirements list.

Use pip install -r requirements.txt to install the packages in your requirements list.

One more piece of information. Venture into your environment folder. In there, you’ll see /bin. /lib, and pyenv.cfg. The configuration file lists some versions and the path to your user executable and /bin lists the executables present in your environment. A little further into /lib and you’ll find /lib/python3.8/site-packages which lists all the packages you have installed in your virtual environment.

And that’s it. Virtual environments help keep your projects organized since a lot of the time, requirements will overlap or versions won’t play nice together. Definitely a good habit to get into.