Creating a Virtual Environment – Real Python
This lesson covers how to create a virtual environment in a project folder. You learned that following the steps below will install a self contained Python environment in your project directory:
- Create a project directory
- Change into the project directory
- Run
python3 -m venv <name_of_virtualenv>
00:00
So, first of all, we’re going to take a look at where the global environment currently lives, and we can do that with the which command. In this case, I’m going to be using Python 3, which means that I’m going to add this 3 suffix to all of my commands here, like pip3, python3, and so on. All right, so the first thing that we’re going to do is we’re going to take a look at where the global environment currently lives.
00:25
And I’m going to do that with the which command, which tells me the path to a file or to an executable. And in this case, I’m looking at the pip3 command because I’m using Python 3 here.
00:37
So if I run this, it tells me that my Python install lives inside /usr/local/bin/—or, my pip install lives inside /usr/local/bin/. This is typical if you’ve installed that through homebrew on macOS, for example.
00:50 Now, I’m going to pretend I’ll be working on a new Python project here, so I’m going to create a new directory for this project, and then I’m going to change into this project directory.
01:02
And what I’m going to do now is I’m going to create a virtual environment inside this folder here. So, what I’m going to do here, I’m going to use the magic incantation python3 -m venv, which stands for virtual environment, and I’m just going to tell it to create a virtual environment inside this my-python-project/ folder, and I want it to create that inside a new subdirectory called venv, which is just a naming convention that I like to use.
01:30
And this is going to set up a new virtual environment. This should finish any minute now. All right, so we just created the new virtual environment, and now when I look at the contents of my project folder, previously it was empty and now I’ve got this venv/ folder in there, and then when we look inside it, you can see there’s a bunch more directories and pretty much, like, a full Python install. And we can drill down further just to show you that there’s a bunch of stuff in this folder here!
02:00
So, when we just list a directory tree here, you can see that we’ve got this bin/ folder, this include/ folder, lib/ folder.
02:09 This is where all of our Python third-party packages are going to live, and they were seeded with some basic stuff, like a very basic Python install. And that’s what a virtual environment does. Now we’ve pretty much got this tiny self-contained virtual environment—a Python environment—installed inside our project folder.