在Windows 7上添加Python路径

问题:在Windows 7上添加Python路径

我一直在尝试在Windows 7上将Python路径添加到命令行中,但是无论我尝试哪种方法,似乎都没有任何效果。我使用了该set命令,尝试通过“编辑环境”变量提示符等添加它。

此外,如果我在命令行上运行set命令,它将列出此内容

python = c:\python27

但是它仍然无法识别Python命令。

阅读文档以及其他各种资源似乎无济于事。

编辑:为了进一步说明,我在编辑环境提示中将Python可执行文件的路径附加到PATH。似乎不起作用。

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.


回答 0

  1. 按住Win并按Pause
  2. 单击高级系统设置。
  3. 单击环境变量。
  4. 追加;C:\python27Path变量。
  5. 重新启动命令提示符。
  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.

回答 1

在Windows中设置环境变量时,我在很多情况下都出错了。我认为我应该在这里分享我过去的一些错误,希望对别人有所帮助。(这些适用于所有环境变量,不仅适用于设置Python路径)

当心这些可能的错误:

  1. 杀死并重新打开您的Shell窗口:对环境变量进行更改后,您必须重新启动要对其进行测试的窗口。
  2. 设置变量时没有空间。请确保您添加;C:\Python27无任何空格。(通常C:\SomeOther; C:\Python27在分号后尝试使用空格(␣)是不正确的。)
  3. 阐明完整路径时,请使用向后斜线。尝试时会看到正斜杠,echo $PATH但只有反斜杠对我有用。
  4. 不要添加最后的反斜杠。只有C:\Python27C:\Python27\

希望这对某人有帮助。

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.


回答 2

以管理员权限打开cmd .exe(右键单击应用程序)。然后输入:

setx路径“%path%; C:\ Python27;”

请记住以分号结尾,并且不要包含斜杠。

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.


回答 3

我已经很久没有这个问题了。我以各种方式将其添加到我的路径中,但这终于对我有用:

  1. 右键单击“我的电脑”
  2. 点击“属性”
  3. 点击侧面板中的“高级系统设置”
  4. 点击“环境变量”
  5. 点击系统变量下面的“新建”
  6. 输入名称pythonexe(或您想要的任何名称
  7. 在值输入路径你的Python(例如:C:\Python32\
  8. 现在,编辑Path变量(在系统部分),然后添加%pythonexe%;到已经存在的末尾

IDK为什么这样做有效,但对我有用。

然后尝试在命令行中输入“ python”,它应该可以工作!


编辑:

最近,我一直在使用该程序,它似乎运行良好。还有一个看起来也不错,尽管我从未尝试过。

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.


回答 4

尝试将此python.bat文件添加到System32文件夹,然后在键入时命令行将运行pythonpython

python.bat

@C:\Python27\python.exe %*

资源:

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

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


回答 5

您可以使用命令从当前cmd窗口设置路径PATH =。那只会为当前的cmd实例添加它。如果要永久添加,则应将其添加到系统变量。(计算机>高级系统设置>环境变量)

您将转到您的cmd实例,然后放入PATH=C:/Python27/;%PATH%

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%.


回答 6

确保您没有在新目录之前添加空格。

好:旧;旧;旧;新

不好:老;老;老;新

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

Good: old;old;old;new

Bad: old;old;old; new


回答 7

Python带有一个小型工具,可以执行此操作。从命令行运行:

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

确保关闭命令窗口(使用exit或关闭按钮),然后再次打开它。

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.


回答 8

以下程序将python可执行路径和subdir脚本(例如pip和easy_install的安装位置)添加到您的环境中。它从绑定.py扩展名的注册表项中找到python可执行文件的路径。它将删除您环境中的旧python路径。也适用于XP(可能还有Vista)。它仅使用基本Windows安装程序随附的模块。

# 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)

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)

回答 9

我知道这篇文章很旧,但我想补充一点,该解决方案假设使用admin privs。如果您没有这些,可以:

转到控制面板,键入路径(此为Windows 7,现在在搜索框中),然后单击“为您的帐户编辑环境变量”。现在,您将看到环境变量对话框,其顶部为“用户变量”,而其下方为“系统变量”。

您可以作为用户单击顶部的“新建”按钮并添加:

变量名称:PATH
变量值:C:\ Python27

(任何地方都没有空格),然后单击“确定”。重新启动命令提示符后,User变量中的所有PATH都将附加到系统路径的末尾。它不会以任何其他方式替换PATH。

如果要设置特定的完整路径,最好创建一个像这样的批处理文件:

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

将其命名为“ compiler.bat”或双击以启动它。或链接到它。或固定等等…

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…


回答 10

您需要在系统变量中进行更改
-右键单击“我的电脑”
-单击“属性”
-单击侧面板中的“高级系统设置”
-单击环境变量-您将分为两部分变量和系统变量
-在系统变量部分下搜索变量’Path’单击编辑并添加
"C:\Python27;"(不带引号)将其保存
-现在打开命令行类型’path’ 并按Enter,您将看到路径变量已被修改
-现在输入python --version您将看到python版本

完成了

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


回答 11

对于尝试使用Python 3.3+实现此目标的任何人,Windows安装程序现在都提供了一个将python.exe添加到系统搜索路径的选项。在docs中阅读更多内容。

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.


回答 12

使用Windows环境变量始终是一种可怕的经历。最近,我发现了一个令人称奇的工具,称为Rapid Environment Editor,它提供了非常简单的GUI来管理它们。

如果您使用Chocolatey,则可以使用安装它choco install rapidee。否则,请访问http://www.rapidee.com/cn/download

重新阅读此内容,听起来像是有偿的,但是我发誓我不是!一段时间以来,它一直是我工具箱中最有用的实用程序之一,但令我惊讶的是似乎没人知道它。

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.


回答 13

如果Python与其他程序一起安装,例如我的ArcGIS 10.1,则还必须在环境变量中包含指向python.exe路径的所有其他文件夹。

所以我的环境变量看起来像这样:

系统变量>路径>添加 ;C:\Python27\ArcGIS10.1

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


回答 14

这个问题已经很老了,但是我遇到了一个类似的问题,这里没有列出我的特定解决方案:

确保您的PATH中没有不存在的文件夹。

就我而言,我有一堆默认文件夹(Windows,Powershell,Sql Server等),然后是C:\bin我通常使用的自定义,然后进行了其他各种调整,例如c:\python17等等。事实证明,cmd处理器发现c:\bin没有不存在,然后停止处理其余变量。

另外,我不知道如果没有PATH manager,我是否会注意到这一点。它很好地强调了该项目无效的事实。

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.


回答 15

我刚刚使用选项“将python添加到PATH”在Windows 7上安装了Python 3.3。

在PATH变量中,安装程序会自动添加最后一个反斜杠C:\Python33\ ,因此在命令提示符下不起作用(我尝试多次关闭/打开提示符)

我删除了最后的反斜杠,然后它起作用了:C:\Python33

感谢Ram Narasimhan给您的提示4!

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 !


回答 16

我使用cmd在Win7 64位下组织了这样的python环境变量。

PYTHONPATH通过Windows的环境变量菜单设置变量,并将其添加%PYTHONPATH%PATH变量中:

...;%PYTHONPATH%

cmd shell将变量正确扩展为:

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

不要忘记在更改PATH之后重新启动cmd shell。

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.


回答 17

将其写在命令提示符上:

set Path=%path%

用Python文件夹示例的路径替换%path%:

set Path=C:/Python27

write that on your Command Prompt:

set Path=%path%

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

set Path=C:/Python27

回答 18

如果您对设置python的路径感到沮丧,只需下载新版本的python并卸载旧版本的python,并在安装新版本时询问是否设置路径标记并安装

这是最好的方法

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