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.
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.
-
Using the command prompt
Open the command prompt and use the
setcommand to add to thePYTHONPATHenvironment variable.set PYTHONPATH=%PYTHONPATH%;C:\path\to\your\moduleYou can also use the
setxcommand, 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 promptsetx PYTHONPATH %PYTHONPATH%;C:\path\to\your\module -
Using the environment variables settings
You can also add to the
PYTHONPATHenvironment variable using the environment variables settings:- Press the Windows key + R, type
sysdm.cpl, and press Enter. - Click on the Advanced tab and then click on Environment Variables.
- Under User variables (or System variables if you have admin rights) scroll down and find the variable named
PYTHONPATH. If it doesn't exist, click New to create it. - 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;
- Press the Windows key + R, type
-
Using an IDE
If you're using an IDE such as IDLE, PyCharm, or Spyder, you may be able to add to the
PYTHONPATHdirectly through the IDE's settings. The option to add toPYTHONPATHcan 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:
Test whether Python can find your module
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, you've set the PYTHONPATH correctly.
Alternatively, you can append the path directly in your script before importing your modules:
Append path before importing a module
import sys
sys.path.append(r"C:\path\to\your\module")Also, if you are using the Anaconda distribution, it's worth checking the conda documentation on how to add new paths to the Python interpreter on Windows.