139

I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the set command, I've tried adding it through the Edit Environment variables prompt etc.

Further more if I run the set command on the command line it lists this

python = c:\python27

Yet it still doesn't recognize the Python command.

Reading the documentation, and various other sources hasn't seemed to help.

Edit: Just to clarify further, I've appended the path of the Python executable to PATH in edit environment prompt. Doesn't seem to work.

S.L. Barth
  • 7,954
  • 71
  • 47
  • 62
rogerklutz
  • 1,391
  • 2
  • 9
  • 4

21 Answers21

266
  1. Hold Win and press Pause.
  2. Click Advanced System Settings.
  3. Click Environment Variables.
  4. Append ;C:\python27 to the Path variable.
  5. Restart Command Prompt.
melhosseiny
  • 9,416
  • 5
  • 26
  • 47
  • 2
    Yeah, I've already done that. Sorry if I didn't make that clearer in the original question – rogerklutz Jun 11 '11 at 19:58
  • 11
    Ensure that you don't have any spaces in your python and path variables. – Yossi Jun 11 '11 at 21:51
  • 4
    @rogerklutz: Just make sure you're adding ";C:\python27" to the PATH variable that already exists, and not creating a new variable with "C:\python27" as the value. – wassimans May 06 '12 at 20:55
  • 5
    In many cases, you also have to log out and back in after setting the Path variable. – dk123 Nov 05 '13 at 02:34
  • Suffering a similar problem, had done everything but step 5... Thank you for including that. – ReiMasuro Apr 17 '14 at 12:41
  • The main problem with this answer is that not all computers (ex. laptops) have a PAUSE. I think that using kenichi's answer is cross release, and cross hardware. – IronManMark20 Apr 25 '15 at 00:09
  • Small precision (which is what got me): once the path variable has been modified, **click on OK** (do not close by clicking on the X), then click again on OK on the variables window. If you don't, the changes will not be saved (not so obvious when you're used to Linux). – Right leg Jun 09 '17 at 09:45
  • What is the difference for setting environment variable for User and System? – Starlord Aug 29 '17 at 18:38
112

When setting Environmental Variables in Windows, I have gone wrong on many, many occasions. I thought I should share a few of my past mistakes here hoping that it might help someone. (These apply to all Environmental Variables, not just when setting Python Path)

Watch out for these possible mistakes:

  1. Kill and reopen your shell window: Once you make a change to the ENVIRONMENTAL Variables, you have to restart the window you are testing it on.
  2. NO SPACES when setting the Variables. Make sure that you are adding the ;C:\Python27 WITHOUT any spaces. (It is common to try C:\SomeOther; C:\Python27 That space (␣) after the semicolon is not okay.)
  3. USE A BACKWARD SLASH when spelling out your full path. You will see forward slashes when you try echo $PATH but only backward slashes have worked for me.
  4. DO NOT ADD a final backslash. Only C:\Python27 NOT C:\Python27\

Hope this helps someone.

Ram Narasimhan
  • 21,558
  • 4
  • 42
  • 53
  • 1
    The reason that I chose this answer is that most of the time the PATH get's broken because of one of these 4 things. The easy part is doing it correctly, the hard part is noticing when you did it incorrectly! – grettke Jan 05 '15 at 01:25
  • 1
    The command `echo $path` is only valid if you're running a bash shell under windows (e.g. MinGW). The windows command prompt command is `echo %path%` – Bruce Peterson Jul 17 '15 at 20:44
  • 2
    I haven't found the trailing backlash to be problematic. Am I missing something? – mystrdat Nov 12 '15 at 16:58
51

Open cmd.exe with administrator privileges (right click on app). Then type:

setx path "%path%;C:\Python27;"

Remember to end with a semi-colon and don't include a trailing slash.

A.L
  • 9,074
  • 9
  • 55
  • 87
kenichi
  • 649
  • 7
  • 14
  • 3
    +1- This lets you add to the path without needing admin privileges. However, I am not sure the %path% is needed. On my Windows 7 system, new cmd windows now have two copies of the previous paths. – Paul Lynch Nov 07 '14 at 15:38
  • %path% is your old path variable value, it is there so "C:\Python27;" will be appended to your existing path. – infantry Oct 12 '20 at 02:40
32

I've had a problem with this for a LONG time. I added it to my path in every way I could think of but here's what finally worked for me:

  1. Right click on "My computer"
  2. Click "Properties"
  3. Click "Advanced system settings" in the side panel
  4. Click "Environment Variables"
  5. Click the "New" below system variables
  6. in name enter pythonexe (or anything you want)
  7. in value enter the path to your python (example: C:\Python32\)
  8. Now edit the Path variable (in the system part) and add %pythonexe%; to the end of what's already there

IDK why this works but it did for me.

then try typing "python" into your command line and it should work!


Edit:

Lately I've been using this program which seems to work pretty well. There's also this one which looks pretty good too, although I've never tried it.

JustGage
  • 1,284
  • 16
  • 19
16

Try adding this python.bat file to System32 folder and the command line will now run python when you type in python

python.bat

@C:\Python27\python.exe %*

Source:

https://github.com/KartikTalwar/dotfiles/blob/master/bat/python.bat

Kartik
  • 8,035
  • 8
  • 45
  • 52
14

You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)

You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%.

Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165
Anirudh Ramanathan
  • 43,868
  • 20
  • 121
  • 177
11

Make sure you don't add a space before the new directory.

Good: old;old;old;new

Bad: old;old;old; new

Mike Pateras
  • 14,127
  • 29
  • 93
  • 131
9

Python comes with a small utility that does just this. From the command line run:

c:\python27\tools\scripts\win_add2path.py

Make sure you close the command window (with exit or the close button) and open it again.

Udi
  • 24,758
  • 8
  • 84
  • 116
  • 1
    As for me, it does changes the register but none app will be affected until you manually confirm the changes via std GUI dialog. Restarting an app does not help. It looks like a kind of broadcasting is needed also. – Pavel Vlasov Jan 25 '14 at 20:18
  • This worked for me on 8.1 and seems easier than other approaches. A window/box opens up and asks what you want to run. Select Other and then navigate back to c:\python27 and pick the python executable (.exe). The effect appears to be permanent so you need do that only once. You will need to run win_add2path.py for every user but you don't get the box after the first time. – user2099484 Dec 23 '15 at 07:44
8

The following program will add the python executable path and the subdir Scripts (which is where e.g. pip and easy_install are installed) to your environment. It finds the path to the python executable from the registry key binding the .py extension. It will remove old python paths in your environment. Works with XP (and probably Vista) as well. It only uses modules that come with the basic windows installer.

# coding: utf-8

import sys
import os
import time
import _winreg
import ctypes

def find_python():
    """
    retrieves the commandline for .py extensions from the registry
    """
    hKey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
                           r'Python.File\shell\open\command')
    # get the default value
    value, typ = _winreg.QueryValueEx (hKey, None)
    program = value.split('"')[1]
    if not program.lower().endswith(r'\python.exe'):
        return None
    return os.path.dirname(program)

def extend_path(pypath, remove=False, verbose=0, remove_old=True,
                script=False):
    """
    extend(pypath) adds pypath to the PATH env. variable as defined in the
    registry, and then notifies applications (e.g. the desktop) of this change.
    !!! Already opened DOS-Command prompts are not updated. !!!
    Newly opened prompts will have the new path (inherited from the 
    updated windows explorer desktop)
    options:
    remove (default unset), remove from PATH instead of extend PATH
    remove_old (default set), removes any (old) python paths first
    script (default unset), try to add/remove the Scripts subdirectory 
        of pypath (pip, easy_install) as well
    """
    _sd = 'Scripts' # scripts subdir
    hKey = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE,
               r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
               0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE)

    value, typ = _winreg.QueryValueEx (hKey, "PATH")
    vals = value.split(';')
    assert isinstance(vals, list)
    if not remove and remove_old:
        new_vals = []
        for v in vals:
            pyexe = os.path.join(v, 'python.exe')
            if v != pypath and os.path.exists(pyexe):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            if script and v != os.path.join(pypath, _sd) and \
               os.path.exists(v.replace(_sd, pyexe)):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            new_vals.append(v)
        vals = new_vals
    if remove:
        try:
            vals.remove(pypath)
        except ValueError:
            if verbose > 0:
                print 'path element', pypath, 'not found'
            return
        if script:
            try:
                vals.remove(os.path.join(pypath, _sd))
            except ValueError:
                pass
            print 'removing from PATH:', pypath
    else:
        if pypath in vals:
            if verbose > 0:
                print 'path element', pypath, 'already in PATH'
            return
        vals.append(pypath)
        if verbose > 1:
            print 'adding to PATH:', pypath
        if script:
            if not pypath + '\\Scripts' in vals:
                vals.append(pypath + '\\Scripts')
            if verbose > 1:
                print 'adding to PATH:', pypath + '\\Scripts'
    _winreg.SetValueEx(hKey, "PATH", 0, typ, ';'.join(vals) )
    _winreg.SetValueEx(hKey, "OLDPATH", 0, typ, value )
    _winreg.FlushKey(hKey)
    # notify other programs
    SendMessage = ctypes.windll.user32.SendMessageW
    HWND_BROADCAST = 0xFFFF
    WM_SETTINGCHANGE = 0x1A
    SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment')
    if verbose > 1:
        print 'Do not forget to restart any command prompts'

if __name__ == '__main__':
    remove = '--remove' in sys.argv
    script = '--noscripts' not in sys.argv
    extend_path(find_python(), verbose=2, remove=remove, script=script)
Anthon
  • 51,019
  • 25
  • 150
  • 211
  • This ruined my PATH. Here is a fixed version (I also removed remove_old, which is impossible* to get right): https://gist.github.com/anonymous/fb5d176ab91dccbd0ebd * yes – Aur Saraf Dec 01 '14 at 23:00
6

I know this post is old but I'd like to add that the solutions assume admin privs. If you don't have those you can:

Go to control panel, type path (this is Windows 7 now so that's in the Search box) and click "Edit Environment variables for your account". You'll now see the Environment Variable dialog with "User variables" on the top and "System variables" below.

You can, as a user, click the top "New" button and add:

Variable name: PATH
Variable value: C:\Python27

(no spaces anywhere) and click OK. Once your command prompt is restarted, any PATH in the User variables is appended to the end of the System Path. It doesn't replace the PATH in any other way.

If you want a specific full path set up, you're better off creating a batch file like this little one:

@echo off
PATH C:\User\Me\Programs\mingw\bin;C:\User\Me\Programs;C:\Windows\system32
title Compiler Environment - %Username%@%Computername%
cmd

Call it "compiler.bat" or whatever and double click to start it. Or link to it. Or pin it etc...

carveone
  • 819
  • 9
  • 13
6

You need to make changes in your system variable
-- Right click on "My computer"
-- Click "Properties"
-- Click "Advanced system settings" in the side panel
-- Click on Environment Variable -- You will two sections of user variable and system variable
-- Under system variable section search for the variable 'Path' click on edit and add
"C:\Python27;" (without quotes) save it
-- Now open command line type 'path' hit enter you will see path variable has been modified
-- Now type python --version you will see the python version

And it is done

Delimitry
  • 2,813
  • 4
  • 25
  • 36
Avinash Agrawal
  • 848
  • 1
  • 8
  • 15
5

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.

Andreas Bergström
  • 11,092
  • 5
  • 49
  • 46
  • 1
    This is what I used, because I was having trouble finding the exact path of the install. Start up the installer, hit 'Modify' and then on the Optional Features, click next, then check the box to add Python to the system path and hit Finish. – Rishi Jul 27 '16 at 18:23
4

Working with Windows environment variables is always a horrible experience. Recently, I found an amazing tool called Rapid Environment Editor, which gives an awesomely simple GUI for managing them.

If you use chocolatey, you can install it using choco install rapidee. Otherwise, take a look at http://www.rapidee.com/en/download

Re-reading this, it sounds like a paid shill, but I swear I'm not! It's just been one of the most useful utilities in my toolkit for a while and I'm surprised no one seems to know about it.

Rob H
  • 1,760
  • 13
  • 25
3

If Python was installed with another program, such as ArcGIS 10.1 in my case, then you also must include any extra folders that path to the python.exe in your Environment Variables.

So my Environment Variables looks like this:

System variables > Path > add ;C:\Python27\ArcGIS10.1

geominded
  • 164
  • 1
  • 8
2

This question is pretty old, but I just ran into a similar problem and my particular solution wasn't listed here:

Make sure you don't have a folder in your PATH that doesn't exist.

In my case, I had a bunch of default folders (Windows, Powershell, Sql Server, etc) and then a custom C:\bin that I typically use, and then various other tweaks like c:\python17, etc. It turns out that the cmd processor was finding that c:\bin didn't exist and then stopped processing the rest of the variable.

Also, I don't know that I ever would have noticed this without PATH manager. It nicely highlighted the fact that that item was invalid.

Chris Phillips
  • 9,741
  • 3
  • 31
  • 43
2

I just installed Python 3.3 on Windows 7 using the option "add python to PATH".

In PATH variable, the installer automatically added a final backslash: C:\Python33\ and so it did not work on command prompt (i tried closing/opening the prompt several times)

I removed the final backslash and then it worked: C:\Python33

Thanks Ram Narasimhan for your tip #4 !

Arnaud
  • 111
  • 3
  • 12
2

I organized my python environment variable like this under Win7 64-bit using cmd.

I set the variable PYTHONPATH via environment variable menue of windows and added %PYTHONPATH% to the PATH variable:

...;%PYTHONPATH%

The cmd shell expands the variable correctly to this:

C:\>echo %PYTHONPATH%
C:\python27;c:\python27\lib;C:\python27\scripts

Do not forget to restart cmd shell after changing PATH.

0

write that on your Command Prompt:

set Path=%path%

Replace %path% by the Path of your Python Folder Example:

set Path=C:/Python27
Skiller Dz
  • 739
  • 7
  • 16
0

For people getting the windows store window when writing python in the console, all you have to do is go to configuration -> Manage app execution aliases and disable the toggles that say python.

then, add the following folders to the PATH.

C:\Users\alber\AppData\Local\Programs\Python\Python39\
C:\Users\alber\AppData\Local\Programs\Python\Python39\Scripts\
Raikish
  • 416
  • 1
  • 5
  • 15
0

If you are on Windows, run this:

C:\Users\username> cd C:\bin
C:\bin> echo @php "%~dp0phpunit.phar" %* > phpunit.cmd

Make sure, you have installed phpuunit as stated here: https://phpunit.de/manual/6.5/en/installation.html

Then:

phpunit path-to-your-test
Tim Long
  • 1,768
  • 1
  • 19
  • 24
-2

If you have got frustrated by setting the path for the python just download the new version of python uninstall the older version of the python and while installing the new version it will ask whether to set path mark that and install

its the best way