Python
PYTHONPATH
Windows
Modules
Environment Variables

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Python's extensibility and modularity are among its greatest strengths, allowing users to create and import customized modules and packages. However, to leverage these, Python must know where to look for them. This is where PYTHONPATH , an environment variable, plays a crucial role. In this article, you’ll learn how to set or modify PYTHONPATH in a Windows environment to ensure Python can locate your modules and packages.

Understanding PYTHONPATH

PYTHONPATH is an environment variable used by Python to specify the locations where the Python interpreter should look for modules and packages. It supplements the default search paths hardcoded into Python and can be particularly useful for development purposes or when working with virtual environments.

Step-by-Step Guide to Customize PYTHONPATH on Windows

Method 1: Temporary PYTHONPATH for a Session

  1. Open Command Prompt: Open the command prompt from the Start Menu or by pressing Win + R , typing cmd , and pressing Enter .
  2. Set the PYTHONPATH: You can temporarily set the PYTHONPATH for the current session using the set command. For instance:
    • Right-click on 'This PC' or 'Computer' on the desktop and select 'Properties'.
    • Click on 'Advanced system settings' from the left sidebar.
    • Under the 'System Properties' window, switch to the 'Advanced' tab, and click 'Environment Variables'.
    • In the 'Environment Variables' window, check if a PYTHONPATH variable already exists under 'User variables' or 'System variables'.
    • If it exists, select it and click 'Edit'. Otherwise, click 'New' to create a new environment variable.
      • Variable name: PYTHONPATH
      • Variable value: C:\path\to\your\modules (use semicolons to separate multiple paths, e.g., C:\path\one;C:\path\two )
  • Using .pth Files: Alternatively, you can add paths by creating a .pth file in one of the site-packages directories. Python reads these files to automatically include directories listed inside them.
  • Environment Variable Precedence: Be aware that PYTHONPATH settings are overridden by the sys.path list manipulated during script execution. The initial entries in sys.path take precedence.
  • Check Existing sys.path: To see the current module search paths used by Python:

Course illustration
Course illustration

All Rights Reserved.