简体   繁体   English

将 Python 添加到 Windows 上的 PATH

[英]Adding Python to PATH on Windows

I've been trying to add the Python path to the command line on Windows, yet no matter the method I try, nothing seems to work.我一直在尝试将 Python 路径添加到 Windows 的命令行中,但无论我尝试哪种方法,似乎都没有任何效果。 I've used the set command, I've tried adding it through the Edit Environment Variables prompt, etc.我使用了set命令,我尝试通过编辑环境变量提示等添加它。

Furthermore, if I run the set command on the command line it lists this.此外,如果我在命令行上运行 set 命令,它会列出这个。

python = c:\python27

Yet it still doesn't recognize the Python command.但它仍然无法识别 Python 命令。

Reading the documentation, and various other sources haven't seemed to help.阅读文档和其他各种来源似乎没有帮助。

Just to clarify further, I've appended the path of the Python executable to PATH in the Edit Environment prompt.为了进一步澄清,我在编辑环境提示中将 Python 可执行文件的路径附加到 PATH 中。 Doesn't seem to work.似乎不起作用。

  1. Hold Win and press Pause .按住Win并按Pause
  2. Click Advanced System Settings.单击高级系统设置。
  3. Click Environment Variables.单击环境变量。
  4. Append ;C:\python27 to the Path variable. Append ;C:\python27Path变量。
  5. Restart Command Prompt.重新启动命令提示符。

When setting Environmental Variables in Windows, I have gone wrong on many, many occasions.在 Windows 中设置环境变量时,我在很多很多场合都出错了。 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) (这些适用于所有环境变量,不仅仅是在设置 Python 路径时)

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.杀死并重新打开您的 shell window:一旦您更改了环境变量,您必须重新启动您正在测试它的 window。
  2. NO SPACES when setting the Variables.设置变量时没有空格 Make sure that you are adding the ;C:\Python27 WITHOUT any spaces.确保添加;C:\Python27没有任何空格。 (It is common to try C:\SomeOther; C:\Python27 That space (␣) after the semicolon is not okay.) (通常尝试C:\SomeOther; C:\Python27分号后面的那个空格(␣)是不行的。)
  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.当您尝试echo $PATH时,您会看到正斜杠,但只有反斜杠对我有用。
  4. DO NOT ADD a final backslash .不要添加最后的反斜杠 Only C:\Python27 NOT C:\Python27\只有C:\Python27不是C:\Python27\

Hope this helps someone.希望这可以帮助某人。

Open cmd .exe with administrator privileges (right click on app).使用管理员权限打开cmd .exe(右键单击应用程序)。 Then type:然后输入:

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

Remember to end with a semi-colon and don't include a trailing slash.请记住以分号结尾,并且不要包含尾部斜杠。

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)在名称中输入pythonexe (或任何你想要的)
  7. in value enter the path to your python (example: C:\Python32\ )在值中输入 python 的路径(例如: C:\Python32\
  8. Now edit the Path variable (in the system part) and add %pythonexe%;现在编辑 Path 变量(在系统部分)并添加%pythonexe%; to the end of what's already there到已经存在的东西的尽头

IDK why this works but it did for me. IDK 为什么这有效,但它对我有用。

then try typing "python" into your command line and it should work!然后尝试在命令行中输入“python”,它应该可以工作!


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.还有这个看起来也不错,虽然我从来没有尝试过。

Try adding this python.bat file to System32 folder and the command line will now run python when you type in python尝试将此python.bat文件添加到System32文件夹,当您输入 python 时,命令行现在将运行python

python.bat python.bat

@C:\Python27\python.exe %*

Source:资源:

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

You can set the path from the current cmd window using the PATH = command.您可以使用PATH =命令从当前 cmd window设置路径。 That will only add it for the current cmd instance.这只会为当前的 cmd 实例添加它。 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% .您将转到您的 cmd 实例,然后输入PATH=C:/Python27/;%PATH%

Make sure you don't add a space before the new directory.确保不要在新目录之前添加空格。

Good: old;old;old;new好:旧的;旧的;旧的;新的

Bad: old;old;old;坏的:旧的;旧的;旧的; new新的

Python comes with a small utility that does just this . Python 附带了一个小型实用程序,可以做到这一点 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.确保关闭命令 window(带有exit或关闭按钮)并再次打开它。

The following program will add the python executable path and the subdir Scripts (which is where eg pip and easy_install are installed) to your environment.以下程序会将 python 可执行路径和子目录脚本(例如 pip 和 easy_install 安装在其中)添加到您的环境中。 It finds the path to the python executable from the registry key binding the.py extension.它从绑定 .py 扩展名的注册表项中找到 python 可执行文件的路径。 It will remove old python paths in your environment.它将删除您环境中的旧 python 路径。 Works with XP (and probably Vista) as well.也适用于 XP(可能还有 Vista)。 It only uses modules that come with the basic windows installer.它仅使用基本 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)

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". Go 到控制面板,输入路径(现在是 Windows 7,所以它在搜索框中),然后单击“为您的帐户编辑环境变量”。 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变量名: PATH
Variable value: C:\Python27变量值: 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.重新启动命令提示符后,用户变量中的任何 PATH 都将附加到系统路径的末尾。 It doesn't replace the PATH in any other way.它不会以任何其他方式替换 PATH 。

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.将其称为“compiler.bat”或其他名称,然后双击启动它。 Or link to it.或者链接到它。 Or pin it etc...或者别针之类的...

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 -- 现在打开命令行类型'path'回车你会看到路径变量已经被修改
-- Now type python --version you will see the python version -- 现在输入python --version你会看到 python 版本

And it is done它完成了

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.对于任何尝试使用 Python 3.3+ 来实现此目的的人,Windows 安装程序现在包含一个选项,可将 python.exe 添加到系统搜索路径。 Read more in the docs .文档中阅读更多内容。

Working with Windows environment variables is always a horrible experience.使用 Windows 环境变量总是一种可怕的体验。 Recently, I found an amazing tool called Rapid Environment Editor, which gives an awesomely simple GUI for managing them.最近,我发现了一个很棒的工具,叫做 Rapid Environment Editor,它提供了一个非常简单的 GUI 来管理它们。

If you use chocolatey, you can install it using choco install rapidee .如果您使用巧克力,您可以使用choco install rapidee安装它。 Otherwise, take a look at http://www.rapidee.com/en/download否则,看看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.一段时间以来,它一直是我的工具包中最有用的实用程序之一,我很惊讶似乎没有人知道它。

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.如果 Python 与另一个程序一起安装,例如我的 ArcGIS 10.1,那么您还必须在环境变量中包含指向 python.exe 的任何额外文件夹。

So my Environment Variables looks like this:所以我的环境变量看起来像这样:

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

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.确保您的 PATH 中没有不存在的文件夹。

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. 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 cmd 处理器发现c:\bin不存在,然后停止处理变量的 rest。

Also, I don't know that I ever would have noticed this without PATH manager .另外,我不知道如果没有PATH manager我会注意到这一点。 It nicely highlighted the fact that that item was invalid.它很好地突出了该项目无效的事实。

I just installed Python 3.3 on Windows 7 using the option "add python to PATH".我刚刚使用“将 python 添加到路径”选项在 Windows 7 上安装了 Python 3.3。

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)在 PATH 变量中,安装程序自动添加了最后一个反斜杠C:\Python33\因此它在命令提示符下不起作用(我尝试关闭/打开提示符几次)

I removed the final backslash and then it worked: C:\Python33我删除了最后的反斜杠,然后它起作用了: C:\Python33

Thanks Ram Narasimhan for your tip #4 !感谢 Ram Narasimhan 的提示 #4!

I organized my python environment variable like this under Win7 64-bit using cmd.我使用 cmd 在 Win7 64 位下组织了我的 python 环境变量。

I set the variable PYTHONPATH via environment variable menue of windows and added %PYTHONPATH% to the PATH variable:我通过 windows 的环境变量菜单设置变量PYTHONPATH并将%PYTHONPATH%添加到PATH变量中:

...;%PYTHONPATH%

The cmd shell expands the variable correctly to this: cmd shell 将变量正确扩展为:

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

Do not forget to restart cmd shell after changing PATH.更改 PATH 后不要忘记重新启动 cmd shell。

My system is Windows7 32bit, installed Python 2.7.12 (because pdfminer does not support Python 3.X....T^T)我的系统是Windows7 32bit,安装了Python 2.7.12(因为pdfminer不支持Python 3.X....T^T)

Had the same problem that my command window recognises the word “python”.有同样的问题,我的命令 window 识别单词“python”。

It turned out that in PATH variable, automatically added a final backslash: C:\Python33\ (same as Charlie mentioned above)原来在PATH变量中,自动加了一个最后的反斜杠:C:\Python33\(和上面提到的查理一样)

Remove the backslash.删除反斜杠。 all works fine.一切正常。

write that on your Command Prompt:在命令提示符上写下:

set Path=%path%

Replace %path% by the Path of your Python Folder Example:用 Python 文件夹的路径替换 %path% 示例:

set Path=C:/Python27

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. 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.然后,将以下文件夹添加到 PATH。

C:\Users\alber\AppData\Local\Programs\Python\Python39\
C:\Users\alber\AppData\Local\Programs\Python\Python39\Scripts\

If you are on Windows, run this:如果您使用的是 Windows,请运行以下命令:

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确保您已按照此处所述安装了 ppuunit: https://phpunit.de/manual/6.5/en/installation.html

Then:然后:

phpunit path-to-your-test

For an anaconda3 installation the paths to add are:对于anaconda3安装,要添加的路径是:

%USERPROFILE%\anaconda3\
%USERPROFILE%\anaconda3\Scripts\
%USERPROFILE%\anaconda3\Library\bin\

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

its the best way这是最好的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM