Virtual Environments

Background

Before we start working with Python, we are going to create a virtual environment. Why? Because they prevent chaos. You’re very likely not going to have just one Python project. Without virtual environments, your projects and their things that make them work are going to get all jumbled up.

We will not be installing any new Python packages in our virtual environment during this course, but we still want to use a virtual environment because:

  1. Inside our virtual environment we don’t need to specify which version of Python we use, we can just call python
  2. It is a good practice in general to use a separate virtual environment for every project because chaos is no fun

Creating a Directory

First, open a command prompt or terminal window, create a new folder in your home directory (or wherever you want to save your classwork) named human_python, and change into the directory.

Creating the Virtual Environment

Now inside this new human_python directory, we will create our virtual environment.

On Windows, enter these 2 commands:

> py -3.6 -m venv humanpython
> humanpython\Scripts\activate

On OSX and Linux, enter these commands:

$ python3.6 -m venv humanpython
$ source humanpython/bin/activate

The first command creates the virtual environment, which is stored in a new folder (created in human_python) named humanpython. The second command activates the environment.

Note

For my own projects, I like to use a tool called <Virtual Env Wrapper ‘https://virtualenvwrapper.readthedocs.io/en/latest/>. Don’t worry about that today, but maybe tuck the idea away in your mind because it has some cool features.

Activating the Virtual Environment

From now on, whenever you open a new command or terminal window to work on this class, you will need to change directories into the human_python folder and activate your virtual environment.

Activating on Windows:

> humanpython\Scripts\activate

Activating on OSX and Linux:

$ source humanpython/bin/activate

You can tell that your virtual environment is working when your command prompt is prefixed with (humanpython).

Working in a Virtual Environment

Once your virtual environment is activated, typing python will always run the version of Python that we created our environment with (Python 3.6.5). Type python --version and it should say Python 3.6.5. On Windows, you no longer have to type py -3.6 to get Python 3; and on OSX/Linux, you don’t need to type python3.6.

Our instructions for typing in a command/terminal window will use $ to represent the system prompt and use >>> to represent a Python prompt.