Create a Python virtual Environment on macOS

This article shows how to create a Python Virtual Environment on macOS. You can also create a Virtual Environment on Windows.

Open a Terminal

Create a folder for your project:

Documents $ mkdir exceltest

Navigate to the folder:

Documents $ cd exceltest/
exceltest $

Create the virtual environment

Execute the Python command to create a virtual environment:

exceltest $ python3 -m venv env

A folder env is created. The env folder contains a copy of your Python binary and will contain the packages we install in it. To remove the project, including all packages you installed, just remove the project folder including the env folder.

Here you see the directory listing:

exceltest $ ls
env

Activate the virtual environment

exceltest $ source env/bin/activate
(env) exceltest $

Notice the (env) in front of the prompt. This indicates the activation of the virtual environment.

List installed packages

A new virtual environment has the following packages by default installed:

(env) exceltest $ pip list
Package    Version
---------- -------
pip        19.2.3
setuptools 41.2.0

Install packages

To install packages, execute the pip install command:

(env) exceltest $ pip install openpyxl
Collecting openpyxl
  Downloading openpyxl-3.0.7-py2.py3-none-any.whl (243 kB)
     |████████████████████████████████| 243 kB 2.2 MB/s
Successfully installed et-xmlfile-1.0.1 openpyxl-3.0.7

You can now use the package by importing it in your code.