Setting up Python Virtual Environment

As of May 2020, I am using Python 3.8.2. The following article is configured with the version in mind that I am using. I believe the setup that follows works back as far as Python 3.6 (but I am unsure). See Python.org for the latest documentation. The goal of this article is not to be part of a larger tutorial on Python, as there are plenty of articles available on the topic. I am only writing this down in order to have a quick link to point readers to when I mention my setup for larger projects that I will write articles about later.

In all of my projects, I will first setup a virtual environment to keep all of my code and versioned required libraries in one easy to use folder. This way I do not cause issues with other projects that may need different versions of any one library. Virtual environments are very simple to setup and I highly recommend getting into the practice of using them.

The following assumes that you have already installed Python on your Windows or MacOs computer. As I said earlier, the following works at least in Python 3.8.2 or later. (And possibly several versions earlier)

MacOS

To setup a Python Virtual Environment on MacOS

  • Create a folder to store your project
  • Open a Terminal window at that folder
  • Type the following command to setup the required files
    python3 -m venv .venv
  • To activate the Virtual Environment, enter the following command
    source .venv/bin/activate

If you see (.venv) in front of your command line prompt, then you have setup the environment correctly. If not, see the Troubleshooting section below for helpful resources.

Windows

To setup a Python Virtual Environment on Windows

  • Create a folder to store your project
  • Open a Command window and change directories into that folder
  • Type the following command to setup the required files
    python -m venv .venv
  • To activate the Virtual Environment, enter the following command
    .venv\Scripts\activate.bat

If you see (.venv) in front of your command line prompt, then you have setup the environment correctly. If not, see the Troubleshooting section below for helpful resources.

Troubleshooting

The best source is to go directly to the Python.org documentation. However, as I find some more good tutorials on the topic I will add them here as well.

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *