Adding to pythonpath windows

Как добавить Python в переменную Windows PATH

2 min

Запуск Python с терминала зачастую неизбежен. Однако, если вы впервые установили Python в Windows 10, запуск его через Терминал Windows возможен только в том случае, если он добавлен в переменную среды Windows PATH.

Это может показаться сложным, но бояться нечего. Чтобы помочь вам преодолеть повороты, связанные с добавлением Python в PATH Windows после его установки, давайте рассмотрим варианты и несколько необходимых шагов.

Зачем Добавлять Python В Windows PATH?

Если вам не удалось добавить Python в PATH в вашей ОС Windows, вы не сможете запустить интерпретатор Python, запустить виртуальную среду программирования или выполнить такие команды, как pip install, из терминала.

Мы исследуем лучшие способы создания виртуальных сред Python и управления ими.

Это потому, что, когда вы запускаете любую программу, отличную от программы по умолчанию, из командной строки, машина ищет исполняемый файл в текущей папке или в ПУТИ Windows.

Если его нет в переменной PATH, терминал возвращает ошибку «команда не найдена». Добавление в PATH – это мощный инструмент, даже если вы выполняете команду из созданного или пакетного файла по умолчанию , добавление родительского исполняемого файла в переменную PATH также делает его доступным для вызова из терминала.

Как Вручную Добавить Python В ПУТЬ Windows

Во-первых, если вы не установили Python на свой компьютер, перейдите на веб- сайт python.org, чтобы загрузить и установить предпочитаемую версию.

После успешной установки Python на ваш компьютер проверьте, не добавлен ли он в PATH Windows. Откройте свой терминал и введите python , затем нажмите клавишу Enter . Команда может вернуть ошибку, в которой говорится, что «python не распознается как внутренняя или внешняя команда, работающая программа или пакетный файл», что означает, что Python еще не добавлен в переменную PATH вашего компьютера.

Чтобы запускать программы Python из командной строки, выполните шаги, выделенные ниже.

Найдите Путь Установки Python На Вашем ПК

Чтобы добавить Python в ваш Windows PATH, вам нужно получить путь его установки. Для этого откройте панель поиска Windows и введите python.exe (не нажимайте клавишу Enter ). Затем щелкните правой кнопкой мыши Python.exe, который появляется в появившемся меню, и выберите опцию Открыть расположение файла .

В открывшихся окнах проводника щелкните длинную панель каталогов слева от строки поиска. Выделите и скопируйте весь текст пути в буфер обмена с помощью Ctrl + c . Затем перейдите к следующим шагам ниже.

Далее: Добавить Python В PATH В Пользовательских Переменных

Чтобы добавить Python в PATH в пользовательских переменных , щелкните правой кнопкой мыши « Этот компьютер» и выберите « Свойства» . Оказавшись в меню свойств, нажмите на опцию Advanced system settings . В следующем окне выберите вкладку Advanced и выберите Environment Variables .

Environment Variables меню состоит из двух отдельных частей: верхняя часть называется Пользовательские переменные , а нижняя часть имени системных переменных . Однако в этом случае мы сосредоточимся на пользовательских переменных .

В меню пользовательских переменных найдите переменную с именем Path . Затем вставьте путь, который вы скопировали ранее, в параметр «Значение переменной», используя Ctrl + v, и нажмите « ОК» .

Однако, если вы не можете найти эту переменную, вам может потребоваться ее создать. Для этого нажмите New . Затем в форме имени переменной введите путь и вставьте свой путь Python в поле значения переменной .

Вернитесь в папку пути установки Python и дважды щелкните Scripts, чтобы открыть этот каталог. Затем скопируйте его путь из панели пути в верхней части окон (помимо панели поиска), как вы это делали ранее для пути установки Python.

Читайте также:  Mac os vmware fusion download

Скопировав путь к скриптам, вернитесь к переменным среды . Затем выберите переменную Path и нажмите Edit . Введите точку с запятой после пути к исполняемому файлу Python и вставьте после него путь скриптов, который вы только что скопировали. Затем нажмите ОК .

Добавление Python В PATH С Помощью Параметра Системных Переменных

Вы также можете добавить Python в системную переменную PATH. Хотя это всего лишь альтернатива, и в ней нет необходимости, если вы уже добавили ее в переменные Users .

Чтобы использовать параметр « Системные переменные» , выполните шаги, выделенные выше, для копирования пути Python и его сценария. Затем вернитесь в переменные среды . Затем в сегменте системных переменных найдите переменную с именем Path . Щелкните эту переменную и щелкните Изменить .

В следующем появившемся окне нажмите New и вставьте путь, который вы скопировали ранее, в открывшееся пространство. Повторите этот процесс и для пути скриптов . Затем нажмите ОК и закройте окно переменных среды .

Добавить Python В Windows PATH Автоматически

Вы также можете автоматически добавить Python в PATH Windows во время установки. Хотя этот метод работает не во всех случаях, вы все равно можете попробовать.

Для этого щелкните свой установочный файл и установите флажок « Добавить Python 3.7 в PATH» . Номер версии будет меняться при установке разных версий Python.

Установка этого флажка автоматически добавляет Python в ваш путь к Windows. Это означает, что вы можете запускать команды Python через командную строку сразу после установки.

Подтвердите, Что Python Добавлен В Windows PATH

Чтобы узнать, добавлен ли Python в PATH Windows, откройте терминал и введите python –version , затем нажмите клавишу Enter . Если команда возвращает текущую установленную версию Python, это означает, что вы успешно добавили ее в Windows PATH.

Однако, чтобы проверить, добавили ли вы каталог Scripts в Windows PATH, попробуйте запустить пакет установки pip на терминале, заменив «package» на предпочитаемую вами библиотеку. Если вы установили Python 2.7.9 и выше, команда устанавливает названный пакет, указывая, что вы также успешно добавили скрипты Python в путь.

Помимо добавления Python в PATH Windows, вы можете добавить текстовые редакторы, интегрированные среды разработки (IDE), Git, Node, Anaconda и многие другие программы.

Например, управлять проектом с помощью Sublime Text легко, когда вы открываете терминал в каталоге папки вашего проекта и запускаете subl. команда. Это откроет редактор в вашей текущей папке и отобразит его на боковой панели, еще один экономящий время ярлык для продуктивной работы с Sublime Text .

Permanently add a directory to PYTHONPATH?

Whenever I use sys.path.append , the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH ?

20 Answers 20

You need to add your new directory to the environment variable PYTHONPATH , separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell you’re using ( .profile or whatever, depending on your favorite shell) with a command which, again, depends on the shell in question; in Windows, you can do it through the system GUI for the purpose.

superuser.com may be a better place to ask further, i.e. for more details if you need specifics about how to enrich an environment variable in your chosen platform and shell, since it’s not really a programming question per se.

If you’re using bash (on a Mac or GNU/Linux distro), add this to your

/.bashrc then run source

Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information:

For some reason this doesn’t seem to work in Python 2.7. There you can use:

Then create a .pth file in that directory containing the path you want to add (create the directory if it doesn’t exist).

This works on Windows

  1. On Windows, with Python 2.7 go to the Python setup folder.
  2. Open Lib/site-packages.
  3. Add an example.pth empty file to this folder.
  4. Add the required path to the file, one per each line.
Читайте также:  Приложения маркет для windows phone

Then you’ll be able to see all modules within those paths from your scripts.

In case anyone is still confused — if you are on a Mac, do the following:

  1. Open up Terminal
  2. Type open .bash_profile
  3. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. Save the file, restart the Terminal, and you’re done

You could add the path via your pythonrc file, which defaults to

/.pythonrc on linux. ie.

You could also set the PYTHONPATH environment variable, in a global rc file, such

/.profile on mac or linux, or via Control Panel -> System -> Advanced tab -> Environment Variables on windows.

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

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

22 Answers 22

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)

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

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

along with it. Else it will never work.

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
  4. Click [OK]
  5. Locate the «Path» System variable and click [Edit]

Add the following to the existing variable:

%PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk;

Click [OK] to close all of the windows.

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

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.

From Windows command line:

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.

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

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:

That should take care of your problems

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

Under ‘System Variables’:

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

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

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

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. When the installation is completed, python environment variables are added and you can easily use python everywhere.

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.

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.

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

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

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.

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.

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.

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
  1. Create this folder if it does not exist yet:
  1. Create a file sitecustomize.py 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.

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!

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.

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.

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:

Читайте также:  Если переустановить windows все сотрется
Оцените статью