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

In Windows, you can add to the PYTHONPATH environment variable to make sure that Python can find your modules and packages. There are a few different ways to do this, depending on how you have Python installed and which version you're using.

  1. Using the command prompt

    Open the command prompt and use the set command to add to the PYTHONPATH environment variable.

    set PYTHONPATH=%PYTHONPATH%;C:\path\to\your\module

    You can also use the setx command, which allows you to set environment variables system-wide and persist the changes, if you want to make the changes persist after you close the command prompt

    setx PYTHONPATH %PYTHONPATH%;C:\path\to\your\module
  2. Using the environment variables settings

    You can also add to the PYTHONPATH environment variable using the environment variables settings:

    • Press the windows key + r and type 'sysdm.cpl' and press enter
    • Click on the 'Advanced' tab and then click on 'Environment Variables'
    • Under 'System Variables' scroll down and find the variable named 'PYTHONPATH' and click on 'Edit'
    • Add the path to your module or package to the end of the variable value, separated by a semicolon. For example: C:\path\to\your\module;
  3. Using an IDE

    If you're using an IDE such as IDLE, PyCharm, or Spyder, you may be able to add to the PYTHONPATH directly through the IDE's settings. The option to add to PYTHONPATH can be found in a different place depending on the IDE that you are using.

Once you've added the path to your module or package to the PYTHONPATH environment variable, you can test whether Python can find your module by running the following command in the Python interpreter or in the command prompt :

import sys
print(sys.path)

This will print a list of all the directories that Python is currently searching for modules and packages, if your directory is in that list, then you've set the PYTHONPATH correctly.

It is worth mentioning that some version of python (namely Python 2) and some versions of windows, the PYTHONPATH variable will not be automatically read by the interpreter. in that case, you need to set it in the script before importing your modules.

import sys
sys.path.append("C:\path\to\your\module")

Also, if your are using anaconda distribution, it's worth checking the conda documentation on how to add new paths to the python interpreter on windows.