Programming

Windows 7에서 Python 경로 추가

procodes 2020. 6. 23. 22:11
반응형

Windows 7에서 Python 경로 추가


Windows 7의 명령 줄에 Python 경로를 추가하려고 시도했지만 시도한 방법에 관계없이 아무것도 작동하지 않는 것 같습니다. set명령을 사용했으며 환경 변수 편집 프롬프트 등을 통해 추가하려고했습니다.

명령 줄에서 set 명령을 실행하면 다음이 나열됩니다.

python = c:\python27

그러나 여전히 파이썬 명령을 인식하지 못합니다.

설명서 및 기타 다양한 소스를 읽는 것이 도움이되지 않는 것 같습니다.

편집 : 더 명확히하기 위해 편집 환경 프롬프트에서 Python 실행 파일의 경로를 PATH에 추가했습니다. 작동하지 않는 것 같습니다.


  1. 을 길게 Win누릅니다 Pause.
  2. 고급 시스템 설정을 클릭하십시오.
  3. 환경 변수를 클릭하십시오.
  4. 추가] ;C:\python27받는 Path변수입니다.
  5. 명령 프롬프트를 다시 시작하십시오.

Windows에서 환경 변수를 설정할 때 많은 경우에 잘못되었습니다. 나는 누군가에게 도움이되기를 희망하면서 과거의 실수 몇 가지를 공유해야한다고 생각했습니다. (이것은 파이썬 경로를 설정할 때뿐만 아니라 모든 환경 변수에 적용됩니다)

다음과 같은 실수를 조심하십시오.

  1. 쉘 창 종료 및 다시 열기 : 환경 변수를 변경 한 후에 는 테스트중인 창 다시 시작 해야합니다.
  2. 공백이 변수를 설정하지 않을 때. ;C:\Python27공백없이 추가 해야합니다. ( C:\SomeOther; C:\Python27세미콜론 이후에 그 공간 (␣) 을 시도하는 것이 일반적 이지 않습니다.)
  3. 전체 경로를 철자 할 때는 백 슬래시를 사용 하십시오. 시도 할 때 슬래시가 표시 echo $PATH되지만 역 슬래시 만 나를 위해 일했습니다.
  4. 최종 백 슬래시를 추가하지 마십시오 . C:\Python27하지C:\Python27\

이것이 누군가를 돕기를 바랍니다.


관리자 권한으로 cmd .exe를 엽니 다 (앱을 마우스 오른쪽 버튼으로 클릭). 그런 다음 다음을 입력하십시오.

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

세미콜론으로 끝나고 슬래시를 포함하지 마십시오.


나는 오랫동안 이것에 문제가 있었다. 내가 생각할 수있는 모든 방식으로 내 길에 추가했지만 마침내 나를 위해 일한 것이 있습니다.

  1. "내 컴퓨터"를 마우스 오른쪽 버튼으로 클릭하십시오
  2. "속성"을 클릭하십시오
  3. 측면 패널에서 "고급 시스템 설정"을 클릭하십시오
  4. "환경 변수"를 클릭하십시오
  5. 시스템 변수 아래 "새로 만들기"를 클릭하십시오
  6. 이름으로pythonexe (또는 원하는 것을 입력하십시오 )
  7. 값에 파이썬의 경로를 입력합니다 (예 : C:\Python32\)
  8. 이제 시스템 변수에서 Path 변수를 편집하고 %pythonexe%;이미 존재하는 것의 끝에 추가하십시오

IDK가 왜 효과가 있지만 그것은 나를 위해했습니다.

그런 다음 명령 줄에 "python"을 입력하면 작동합니다!


편집하다:

최근에 나는 이 프로그램사용하여 꽤 잘 작동하는 것 같습니다. 도 있습니다 이것 나는 그것을 시도 적이 있지만, 꽤 좋은 보인다.


python.bat파일을 System32폴더에 추가 하면 입력 할 때 명령 줄이 파이썬을 실행합니다.python

python.bat

@C:\Python27\python.exe %*

출처:

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


명령을 사용하여 현재 cmd 창 에서 경로를 설정할 수 있습니다 PATH =. 현재 cmd 인스턴스에만 추가됩니다. 영구적으로 추가하려면 시스템 변수에 추가해야합니다. (컴퓨터> 고급 시스템 설정> 환경 변수)

cmd 인스턴스로 이동하여을 넣습니다 PATH=C:/Python27/;%PATH%.


새 디렉토리 앞에 공백을 추가하지 마십시오.

좋은 : 오래된; 오래된; 오래된; 새로운

나쁜 : 오래된; 오래된; 오래된; 새로운


파이썬은이 작업을 수행하는 작은 유틸리티를 제공 합니다 . 명령 행에서 다음을 실행하십시오.

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

명령 창 ( exit또는 닫기 단추 사용)을 닫고 다시여십시오.


다음 프로그램은 파이썬 실행 파일 경로와 하위 디렉토리 스크립트 (예 : pip 및 easy_install이 설치된 위치)를 환경에 추가합니다. .py 확장자를 바인딩하는 레지스트리 키에서 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)

이 게시물이 오래되었다는 것을 알고 있지만 솔루션에 관리자 권한이 있다고 덧붙이고 싶습니다. 그것들이 없다면 당신은 할 수 있습니다 :

제어판으로 이동하여 경로를 입력하고 (이는 Windows 7이므로 검색 상자에 있음) "계정의 환경 변수 편집"을 클릭하십시오. 이제 상단에 "사용자 변수"와 아래 "시스템 변수"가있는 환경 변수 대화 상자가 나타납니다.

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


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


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.


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.


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


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.


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 !


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.


My system is Windows7 32bit, installed Python 2.7.12 (because pdfminer does not support Python 3.X....T^T)

Had the same problem that my command window recognises the word “python”.

It turned out that in PATH variable, automatically added a final backslash: C:\Python33\ (same as Charlie mentioned above)

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:

set Path=C:/Python27

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

참고URL : https://stackoverflow.com/questions/6318156/adding-python-path-on-windows-7

반응형