How to create a venv in Python 3

Here are some quick notes on creating a Python 3 venv for Python projects.

Create your project directory:

$ mkdir my_project_name
$ cd my_project_name

Create a venv using Python 3:

$ python3 -m venv .venv

Keep the venv out of your Git repo by adding that directory to your .gitignore file:

$ echo '.venv/' >> .gitignore

Every time you work on the project, activate the venv with this command:

$ source .venv/bin/activate

.venv/bin/activate is just a bash script. You can open it in an editor and look at it if you want. The source command runs the code in the script.

Now you can install Flask or Django (or any other Python library) into the venv using pip:

$ pip install flask

Note that you can use pip instead of pip3 and python instead of python3, because you’re inside of the venv. If you want to see where your venv’s python or pip is located, you can run these commands:

$ which python
$ which pip

You’ll see that those commands will give different locations depending on whether your venv is activated.

To deactivate the venv, just type:

$ deactivate

If you’re using PyCharm, you can find the path to your current Python executable in the venv by typing this while your venv is activated:

$ which python

If anyone has questions, leave a comment below.

Thank you so much.