Python Virtual Environments with venv

See Python: Tips and Tricks for similar articles.

In this tutorial, we will be running some commands at the prompt. The prompt text varies by operating system, terminal type, and settings. We will be using a $. Your prompt text will likely be different.

$ sample command

A virtual environment is a self-contained directory tree that contains a Python interpreter and all the additional non-standard Python packages and modules required for your project.

The major advantage of using virtual environments is that you can set up each project with the specific packages and modules it requires. Another big advantage is that you can easily share that setup with other developers so they can quickly make exact copies of the development environment of your project.

For this tutorial, we are assuming you’re using Visual Studio Code, but you should be able to follow along with any IDE (or no IDE at all).

Create the Virtual Environment

  1. Create a new folder to host your project. Give it a name that makes sense for your project.
  2. Open Visual Studio Code and open the folder you just created.
  3. Open a terminal by selecting Terminal > New Terminal or pressing Ctrl + `.
  4. At the terminal, run the following command:
    $ python -m venv .venv
    You can name this directory whatever want, but it is commonly called “.venv” (notice the prepended dot) to indicate that it is a special directory for holding a virtual environment. This will create and populate a new .venv directory. The contents of that directory will differ by operating system:

    Windows

    • .venv
      • Include
      • Lib
      • Scripts – Contains the Python executable.
      • pyvenv.cfg

    Mac

    • .venv
      • bin – Contains the Python executable.
      • include
      • lib
      • pyvenv.cfg
    Here’s what it looks like on a Mac in VS Code’s Explore panel: python virtual environment with venv vs code explorer venv
  5. To work within your virtual environment, you must first activate it. The command for activating a virtual environment varies by operating system. Run one of the following:

    Windows

    $ .venv/Scripts/activate

    Mac

    $ source .venv/bin/activate
  6. When the virtual environment is activated, its name will always appear enclosed in parentheses before the prompt:
    (.venv) $
    If you don’t see the virtual environment name in parentheses before the prompt, you are not in the virtual environment.
  7. You can now invoke the Python interpreter and/or install additional packages (using pip) within the virtual environment. Because the $PATH environment variable is modified when a virtual enviroment is activated, the executable files are resolved within the virtual environment. Let’s take a look at the value of this environment variable. Run the following command for your environment:

    Windows: PowerShell

    $ $Env:PATH

    Windows: Command Prompt

    $ echo %PATH%

    Mac / Linux

    $ echo $PATH
    You should see the path of the Scripts (Windows) or bin (Mac) directory prepended to the list of paths:
    (.venv) $ $Env:PATH
      C:\Webucator\tutorials\.venv\Scripts;C:…
    Because it is at the beginning of $PATH, the Scripts or bin directory will be scanned first to resolve references to executable files. Once you deactivate the virtual environment, the Scripts and bin directory will be removed from $PATH.
  8. Now, you can install any packages or modules you need for your project. For example, if you want to install Django, just run:
    (.venv) $ pip install django
    After it finishes installing, you will see Django, along with some of its dependencies, listed in the .venv/lib directory:
    • .venv
      • lib
        • __pycache__
        • asgiref
        • asgiref-3.3.4.dist-info
        • django
        • Django-3.2.1.dist-info
        • pip
  9. To deactivate (exit) the virtual environment, run:
    (.venv) $ deactivate
    Now, you are back in the original prompt.
  10. When you no longer need a virtual environment, you can delete it by using operating system commands to delete the folder (e.g., .venv) that was automatically built when you created the virtual environment.

Related Articles

  1. Fixing WebVTT Times with Python
  2. Using Python to Convert Images to WEBP
  3. Scientific Notation in Python
  4. Understanding Python’s __main__ variable
  5. Converting Leading Tabs to Spaces with Python
  6. Python Clocks Explained
  7. Python: isdigit() vs. isdecimal()
  8. Maximum recursion depth exceeded while calling a Python object
  9. When to use Static Methods in Python? Never
  10. Finally, a use case for finally – Python Exception Handling
  11. Python Coding Challenge: Two People with the Same Birthday
  12. How to Create a Simple Simulation in Python – Numeric Data
  13. Collatz Conjecture in Python
  14. Associate Python Files with IDLE
  15. How to find all your Python installations on Windows (and Mac)
  16. Python Color Constants Module
  17. A Python Model for Ping Pong Matches
  18. Bulk Convert Python files to IPython Notebook Files (py to ipynb conversion)
  19. pow(x, y, z) more efficient than x**y % z and other options
  20. Python’s date.strftime() slower than str(), split, unpack, and concatenate?
  21. Bi-directional Dictionary in Python
  22. Creating an Email Decorator with Python and AWS
  23. Change Default autosave Interval in JupyterLab
  24. Basic Python Programming Exercise: A Penny Doubled Every Day
  25. Simple Python Script for Extracting Text from an SRT File
  26. Python Virtual Environments with venv (this article)
  27. Mapping python to Python 3 on Your Mac
  28. How to Make IDLE the Default Editor for Python Files on Windows
  29. How to Do Ternary Operator Assignment in Python
  30. How to Convert Seconds to Years with Python
  31. How to Create a Python Package
  32. How to Read a File with Python
  33. How to Check the Operating System with Python
  34. How to Use enumerate() to Print a Numbered List in Python
  35. How to Repeatedly Append to a String in Python
  36. Checking your Sitemap for Broken Links with Python
  37. How to do Simultaneous Assignment in Python
  38. Visual Studio Code - Opening Files with Python open()
  39. How to Slice Strings in Python
  40. How Python Finds Imported Modules
  41. How to Merge Dictionaries in Python
  42. How to Index Strings in Python
  43. How to Create a Tuple in Python