How to add to the PYTHONPATH in Windows, so it finds my modules/packages? [duplicate]
Asked Answered
C

24

475

I have a directory which hosts all of my Django apps (C:\My_Projects). I want to add this directory to my PYTHONPATH so I can call the apps directly.

I tried adding C:\My_Projects\; to my Windows Path variable from the Windows GUI (My Computer > Properties > Advanced System Settings > Environment Variables). But it still doesn't read the coltrane module and generates this error:

Error: No module named coltrane

Chlordane answered 13/9, 2010 at 15:4 Comment(4)
for "no module named" error: #23418441Capstone
I used site module.Tupi
if you want to run python in command prompt it is answered well here I hope this helps https://mcmap.net/q/81143/-the-python-executable-is-not-recognized-on-windows-10-duplicateSergeant
"I want to add this directory to my PYTHONPATH so I can call the apps directly. I tried adding C:\My_Projects\; to my Windows Path variable" - well, yes, of course that doesn't work: the PATH variable is not the same as the PYTHONPATH variable.Consolidation
C
484

You know what has worked for me really well on windows.

My Computer > Properties > Advanced System Settings > Environment Variables >

Just add the path as C:\Python27 (or wherever you installed python)

OR

Then under system variables I create a new Variable called PythonPath. In this variable I have C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-folders-on-the-path

enter image description here

This is the best way that has worked for me which I hadn't found in any of the docs offered.

EDIT: For those who are not able to get it, Please add

C:\Python27;

along with it. Else it will never work.

Chlordane answered 31/1, 2011 at 20:23 Comment(12)
You probably want to add C:\Python27 in your path.Nan
@PiotrDobrogost that link is broken for me now. Is this the application you recommend: [patheditor2.codeplex.com/](patheditor2 at codeplex)Andromeda
@SteveKoch I'm not sure — you would have to ask project's maintener. I no longer use Path Editor as I switched to much better Rapid Environment EditorCrete
It's also important to add C:\Python27\Scripts to the path so that installed scripts can be run from the shell.Penuchle
Why would you put C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk in PYTHONPATH? Those are already configured. Directories for scripts go in the system PATH. Directories for libraries (that aren't installed to site-packages or the per-user site-packages) go in PYTHONPATH.Vincenty
He probably did that because none of of it particularly clear or well organized in any of the documentation, or in any of the tutorials that I've found. It's all a bit too vague, which is strange considering how, back when I was a young chap and python was just getting started, python modeled itself as the ideal language for programming newbies..Muldon
I had to include %PYTHONPATH% in my PATH as well.Muscatel
Remember restart your computerAtencio
No need to restart computer, just need to open up a new command prompt and it should work.Ogren
Thanks darren.. I know this is an old thread but it helped me in setting up node js.. This worked.. I had Python 3.6 and by default it installs in Program Files. I tried installing it to Python36 after seeing your solution. It did not work. Then I uninstalled Python 3.6 and installed Python 2.7 to Python27 folder and it worked..I had to include %PYTHONPATH% in my PATH as well... Have you found out why this is so?Intercontinental
If you want to open this from the command line, rundll32.exe sysdm.cpl,EditEnvironmentVariables works. I put it in a batch file env.bat.Hondo
for python3.8, Python38-32\Lib doesn't contain lib-tk. This means, isn't required to add lib-tk path in PYTHONPATH?Horned
C
138

Windows 7 Professional I Modified @mongoose_za's answer to make it easier to change the python version:

  1. [Right Click]Computer > Properties >Advanced System Settings > Environment Variables
  2. Click [New] under "System Variable"
  3. Variable Name: PY_HOME, Variable Value:C:\path\to\python\version enter image description here
  4. Click [OK]
  5. Locate the "Path" System variable and click [Edit]
  6. Add the following to the existing variable:

    %PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk; enter image description here

  7. Click [OK] to close all of the windows.

As a final sanity check open a command prompt and enter python. You should see

>python [whatever version you are using]

If you need to switch between versions, you only need to modify the PY_HOME variable to point to the proper directory. This is bit easier to manage if you need multiple python versions installed.

Capuano answered 29/1, 2014 at 13:55 Comment(6)
Tried this and it worked... i would recommend anyone going through the same problem to try this.Surprising
Tried this, it didn't do anything at all.Invalid
I tried the accepted answer above and that didn't work so I would recommend this one.Ampere
By "Variable Value:C:\path\to\python\version" do you mean the address of the directory that included python.exe?Parenthesis
@Parenthesis I mean the wrapping directory that contains the lib, bin, libexec, etc. Typically these directories are named Python[VERSION_NUMBER]/, but I have also seen python/[VERSION_NUMBER]. Hope this helpsCapuano
I tried this and it worked for me. I had to make one small adjustment which was to click New for each of these entries for Windows 10 when adding them to the PATH variable. %PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk; I also needed to add %PY_HOME%\Scripts so I had access to pip and the modules I install with pip such as pylintCommuter
A
124

From Windows command line:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

To set the PYTHONPATH permanently, add the line to your autoexec.bat. Alternatively, if you edit the system variable through the System Properties, it will also be changed permanently.

Anachronistic answered 13/9, 2010 at 15:14 Comment(6)
Worked but everytime I open dos I had to set the path.Chlordane
I prefer to use set path=%PATH%;%PYTHONPATH%;Credulous
Dos and editing autoexec.bat..! Have we suddenly slipped back into the 90s?Ajar
Before this, do echo %PYTHONPATH% if this gives you a path go on, otherwise, do e.g. set PYTHONPATH=.;C:\My_python_lib If you don't, windows will expand %PYTHONPATH% to empty string as expected, it will keep it as %PYTHONPATH% in the PYTHONPATH and everything will break! Sounds crazy but thats how win7 cmd works...Lightly
To make it permanent, use setx instead of set.Nanosecond
Note that the syntax differs if using setx, per @AmitNaidu's suggestion - I think it would be setx PYTHONPATH %PYTHONPATH%;C:\My_python_lib or set PYTHONPATH .;C:\My_python_lib. And note that your path can't contain spaces (see e.g. https://mcmap.net/q/81144/-error-invalid-syntax-default-option-is-not-allowed-more-than-39-2-39-time-s-type-quot-setx-quot-for-usage)Merkel
S
64

These solutions work, but they work for your code ONLY on your machine. I would add a couple of lines to your code that look like this:

import sys
if "C:\\My_Python_Lib" not in sys.path:
    sys.path.append("C:\\My_Python_Lib")

That should take care of your problems

Schleswigholstein answered 13/9, 2010 at 16:11 Comment(1)
Modifying sys.path like this is frowned upon and for good reasons. There are better ways of configuring sys.pathPYTHONPATH environment variable and .pth files.Crete
D
58

Just append your installation path (ex. C:\Python27\) to the PATH variable in System variables. Then close and open your command line and type python.

Deepseated answered 7/2, 2013 at 14:26 Comment(2)
This is answering a completely different question than the one OP was asking.Whitethorn
The question isn't about the PATH that DOS uses to find commands, but the Python path, i.e. sys.path in Python. In most operating systems, Python just uses the system environment variable PYTHONPATH, but Windows seems to be 'special'.Snorter
D
43

Adding Python and PythonPath to the Windows environment:

  1. Open Explorer.
  2. Right-click 'Computer' in the Navigation Tree Panel on the left.
  3. Select 'Properties' at the bottom of the Context Menu.
  4. Select 'Advanced system settings'
  5. Click 'Environment Variables...' in the Advanced Tab
  6. Under 'System Variables':

    1. Add

      • PY_HOME

        C:\Python27
        
      • PYTHONPATH

        %PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk;C:\another-library
        
    2. Append

      • path

        %PY_HOME%;%PY_HOME%\Scripts\
        
Dareece answered 16/9, 2015 at 12:51 Comment(2)
This is the only solution that worked for me. Also, for those of you who do not have administrator rights, just follow the steps above under "User variables for [yourUsername]" and it will work just as well.Flesh
Python on Windows, appreciating node.js a little more right nowKimsey
W
25

The easiest way to do that successfully, is to run the python installer again (after the first installation) and then:

  1. choose Modify.
  2. check the optional features which you want and click Next.
  3. here we go, in "Advanced Options" step you must see an option saying "Add Python to environment variables". Just check that option and click Install. 3rd step When the installation is completed, python environment variables are added and you can easily use python everywhere.
Waggle answered 28/2, 2019 at 20:59 Comment(3)
Setting this variable globally through the Environment Variables settings is not recommended, as it may be used by any version of Python instead of the one that you intend to use.Couchman
learn.microsoft.com/en-gb/windows/python/faqsCouchman
Also, I tried this, does not work. Still not in my path.Antimicrobial
K
19

The easier way to set the path in python is : click start> My Computer >Properties > Advanced System Settings > Environment Variables > second windows >

enter image description here

select Path > Edit > and then add ";C:\Python27\;C:\Python27\Scripts\"

link :http://docs.python-guide.org/en/latest/starting/install/win/

Karren answered 18/6, 2013 at 18:41 Comment(1)
changing system path changed nothing (deleting it too). But typing in admin cmd worked: ftype Python.File="C:\Python27\python.exe" "%1" %*Capstone
F
15

You need to add to your PYTHONPATH variable instead of Windows PATH variable.

http://docs.python.org/using/windows.html

Flaring answered 13/9, 2010 at 15:13 Comment(0)
P
15

You can also add a .pth file containing the desired directory in either your c:\PythonX.X folder, or your \site-packages folder, which tends to be my preferred method when I'm developing a Python package.

See here for more information.

Pardoes answered 1/2, 2013 at 23:31 Comment(0)
C
13

The PYTHONPATH environment variable is used by Python to specify a list of directories that modules can be imported from on Windows. When running, you can inspect the sys.path variable to see which directories will be searched when you import something.

To set this variable from the Command Prompt, use: set PYTHONPATH=list;of;paths.

To set this variable from PowerShell, use: $env:PYTHONPATH=’list;of;paths’ just before you launch Python.

Setting this variable globally through the Environment Variables settings is not recommended, as it may be used by any version of Python instead of the one that you intend to use. Read more in the Python on Windows FAQ docs.

Carbonari answered 25/7, 2019 at 19:56 Comment(0)
P
12
import sys
sys.path.append("path/to/Modules")
print sys.path

This won't persist over reboots or get translated to other files. It is however great if you don't want to make a permanent modification to your system.

Platus answered 28/3, 2017 at 14:28 Comment(2)
+1 for the ability to set paths are run time. while arguably "hacky", when writing a proof of concept or a one-off job, this is perfect and leaves the system unmodified.Modular
I disagree that you only have to do this once. I find that the extra path does not persist past the kernal restartingAdventure
T
12

This question needs a proper answer:

Just use the standard package site, which was made for this job!

and here is how (plagiating my own answer to my own question on the very same topic):


  1. Open a Python prompt and type
>>> import site
>>> site.USER_SITE
'C:\\Users\\ojdo\\AppData\\Roaming\\Python\\Python37\\site-packages'
...

(Alternatively, call python -m site --user-site for the same effect.)

  1. Create this folder if it does not exist yet:
...
>>> import os
>>> os.makedirs(site.USER_SITE)
...

(Or, in Bash, your preferred variant of makedirs -p $(python -m site --user-site).)

  1. Create a file sitecustomize.py (with exactly this filename, or it won't work) in this folder containing the content of FIND_MY_PACKAGES, either manually or using something like the following code. Of course, you have to change C:\My_Projects to the correct path to your custom import location.
...
>>> FIND_MY_PACKAGES = """
import site
site.addsitedir(r'C:\My_Projects')
"""
>>> filename = os.path.join(site.USER_SITE, 'sitecustomize.py')
>>> with open(filename, 'w') as outfile:
...     print(FIND_MY_PACKAGES, file=outfile)

And the next time you start Python, C:\My_Projects is present in your sys.path, without having to touch system-wide settings. Bonus: the above steps work on Linux, too!


Why does this work?

From the documentation of standard library package site:

[Then] an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. [...].

So if you create a module named sitecustomize anywhere in PYTHONPATH, package site will execute it at Python startup. And by calling site.addsitedir, the sys.path can be safely extended to your liking.

Tellurize answered 19/12, 2019 at 14:22 Comment(10)
This is the way to go it seems. A good, cross-platform and long term solution. Great one!Dav
Many thanks for this, this is the only way I've found to make this work for VS Community 2019!Barfly
I followed all the steps,It works, but I must launch sitecustomize.py every time.Dato
@JackGriffin: which file have you placed where? I just verified the steps in Windows 10 under Python 3.8.8. Inside my "My_Projects" folder, I placed a dummypackage.py with a function definition. And within a fresh (I)Python shell, import dummypackage succeeds immediately, without manual intervention. Check variable site.USER_SITE_ENABLED (must be True); maybe it is disabled in your environment.Tellurize
@ojdo: I have Python 3.9.5 on Kubuntu 21.04.The folder I want to 'be public', so to speak, contains a filebox.py file. I followed your instructions, got site.USERSITE path, created customizesite.py there, added the folder as you wrote.Launched customize.py. The folder is in sys.path.**>>>import filebox** : no errors. Closed python prompt and launched it again.The folder is no more in sys.path. In the console, if folder path is the working directory >>> import filebox works. Otherwise I got a ModuleNotFoundError: No module named 'filebox'.Dato
There is no site.USER_SITE_ENABLED on my system, but one site.ENABLE_USER_SITE.Guess they change it in this version.Its value is True.You stated that this works on Linux too.It does, but it's only temporary, at least on my system.Dato
I just verified the steps above on Linux (EndeavourOS, Python 3.9.9, but that should not make any difference). Please note that the file sitecustomize.py must be placed in the directory indicated by site.USER_SITE! Whatever code you place in there will be executed. To verify that the file was executed, you can check the contents of sys.path. I find the .../my_projects path appended to this list in each (I)Python session. You don't use any virtual environments, do you?Tellurize
@JackGriffin: the filename must be exactly sitecustomize.py (or usercustomize.py), but not anything else.Tellurize
@Tellurize in the previous comment I wrote the name incorrectly.The file I created is actually sitecustomize.py.I appreciate your help.Will try again all ASAP.Dato
@JackGriffin, ok, then it is puzzling to me as to why these steps do not work for you. I have been using them since 2015 on various Windows and Linux environments without issue.Tellurize
S
6

In Python 3.4 on windows it worked when I added it to PATH enviroment variable instead of PYTHONPATH. Like if you have installed Python 3.4 in D:\Programming\Python34 then add this at the end of your PATH environment variable

;D:\Programming\Python34

Close and reopen command prompt and execute 'python'. It will open the python shell. This also fixed my Sublime 3 issue of 'python is not recognized as an internal or external command'.

Sleight answered 29/8, 2015 at 20:58 Comment(1)
Yeah, this was the only solution to me (Python 3.x). I really have no idea why %PYTHONPATH% isn't resolved on Path parameter. Call the Scripts' folder wasn't necessary.Toxophilite
F
6

The python 2.X paths can be set from few of the above instructions. Python 3 by default will be installed in C:\Users\\AppData\Local\Programs\Python\Python35-32\ So this path has to be added to Path variable in windows environment.

Fremitus answered 29/6, 2016 at 0:43 Comment(0)
E
5

To augment PYTHONPATH, run regedit and navigate to KEY_LOCAL_MACHINE \SOFTWARE\Python\PythonCore and then select the folder for the python version you wish to use. Inside this is a folder labelled PythonPath, with one entry that specifies the paths where the default install stores modules. Right-click on PythonPath and choose to create a new key. You may want to name the key after the project whose module locations it will specify; this way, you can easily compartmentalize and track your path modifications.

thanks

Evannia answered 13/3, 2013 at 7:41 Comment(0)
G
5

I got it worked in Windows 10 by following below steps.

Under environment variables, you should only add it under PATH of "System Variables" and not under "User Variables". This is a great confusion and eats time if we miss it.

Also, just try to navigate to the path where you got Python installed in your machine and add it to PATH. This just works and no need to add any other thing in my case.I added just below path and it worked.

C:\Users\YourUserName\AppData\Local\Programs\Python\Python37-32

Most important, close command prompt, re-open and then re-try typing "python" to see the version details. You need to restart command prompt to see the version after setting up the path in environment variables.

After restarting, you should be able to see the python prompt and below info when typing python in command prompt:

On typing python in command prompt

Gold answered 5/8, 2019 at 8:10 Comment(0)
J
3

For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.

Joung answered 4/11, 2013 at 9:1 Comment(0)
C
2

This PYTHONPATH variable needs to be set for ArcPY when ArcGIS Desktop is installed.

PYTHONPATH=C:\arcgis\bin (your ArcGIS home bin)

For some reason it never was set when I used the installer on a Windows 7 32-bit system.

Collimate answered 30/11, 2012 at 18:14 Comment(0)
C
1

Maybe a little late, but this is how you add the path to the Windows Environment Variables.

  1. Go to the Environment Variables tab, you do this by pressing Windows key + Pausa inter.

  2. Go to Advanced System Settings.

  3. Click on Environment Variables.

  4. On the lower window search for the 'Path' value.

  5. Select it

  6. Click on Edit

  7. In the end of the line add your instalation folder and the route to 'Scripts' folder.

  8. Click ok, aceptar etc.

You're done, enter cmd and write python from any location of your drive, it should enter the Python program.

Example with my pc (I have Python34)

EXISTING_LINES;C:\Python34;C:\Python34\Scripts\

Hope it helps.

Greetings from Bogotá

Corneous answered 28/3, 2016 at 19:13 Comment(2)
It is indeed a little late, since this answer was already provided five years ago :-) It's also not really what is asked here (since the question is about PYTHONPATH, not PATH)...Kila
What is Pausa inter.?Maddi
A
1

You can set the path variable for easily by command prompt.

  1. Open run and write cmd

  2. In the command window write the following: set path=%path%;C:\python36

  3. press enter.
  4. to check write python and enter. You will see the python version as shown in the picture.

enter image description here

Alvaalvan answered 9/5, 2019 at 16:30 Comment(0)
S
1

While this question is about the 'real' Python, it did come up in a websearch for 'Iron Python PYTHONPATH'. For Iron Python users as confused as I was: It turns out that Iron Python looks for an environment variable called IRONPYTHONPATH.

Linux/Mac/POSIX users: Don't forget that not only does Windows use \ as path separators, but it also uses ; as path delimiters, not :.

Snorter answered 16/10, 2019 at 16:45 Comment(0)
L
0

To make sure Python can find code based on the directory you are executing this code from, if not already there, add to your system environment variable: key PYTHONPATH, value ..

Laural answered 5/7, 2022 at 16:3 Comment(0)
E
0

Before adding a path, its necessary to do some debugging, what path already exists.

Let's say you have to execute python src/main.py

Put the below lines in main.py file and notice what paths python interpreter is looking at:

import sys
print("paths are", sys.path)

If you don't find the path that you need and want to add your path. Follow the below suggestions.

  1. First take note of what PYTHONPATH is already there. This is important if something goes terribly wrong. echo %PYTHONPATH%

  2. Set a temporary python path. Make sure to use CMD and not powershell.

    set PYTHONPATH=%PYTHONPATH%;C:\Users\mentorconnect\

  3. Start new terminal, start virtual environment and check if sys.path worked?

Elyn answered 3/11, 2023 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.