Python exe windows path

How to add Python to Windows PATH

There are few ways in which you can add Python to Windows PATH. In this guide, I’ll share with you two methods that you can use to add Python to Windows path:

  • Via the installation of a recent version of Python
  • Manual entry of the paths

But why would you want to add Python to Windows path in the first place?

Well, if you try to install a Python package using PIP for example, you may get the following error in the Windows Command Prompt:

‘pip’ is not recognized as an internal or external command, operable program or batch file

To overcome this error, you may apply any of the two methods described below.

Method 1: Install a Recent Version of Python

You can easily add Python to Windows path by downloading a recent version of Python, and then checking the box to Add Python to PATH during the installation.

Before you proceed, you may choose to uninstall your previous version of Python if needed.

In my case, the latest version of Python that was available to download was version 3.7.2.

In the Python installation box, just check the box to add Python to PATH as below:

Finish the installation, and you should be good to go.

Alternatively, you may manually add the paths into the Environment variables.

Method 2: Manually add Python to Windows Path

If you wish to stick with your previous version of Python, you may apply the steps below to manually add Python to Windows path.

Note that I’ll be using Windows 10 to demonstrate the steps, but similar principles would apply for previous versions of Windows.

Step 1: Navigate to the Windows Environment Variables screen

To navigate to the Windows Environment Variables screen, where you can add/edit your paths, simply right click on the ‘This PC‘ icon. Then, select ‘Properties.’

Next, click on the ‘Advanced system settings

Finally, click on the ‘Environment Variables…

That should take you to the Environment Variables screen, where you can add/edit your paths.

Click on ‘New…‘ to add the ‘Path’ variable (note that if your ‘Path’ variable already exists, then click on ‘Edit…’ instead):

You should then see the following box, which will allow you to add/edit variables:

Before you type any values, you’ll need to locate the relevant Python paths. The paths that you’ll need to get are:

  • The Python application path, which is the folder where you originally installed Python; and
  • The Python Scripts path. The Scripts folder should be located within the Python application path.
Читайте также:  Альт линукс проверка диска

Here is how my Python application path looks like:

And this is how my Python Scripts path looks like:

Now let’s fill the New User Variable box that you saw earlier:

For the Variable name, type ‘Path‘.

For the Variable value, copy the full Python application path, then use semicolon (as highlighted in yellow below), and finally copy the Python Scripts path.

This is how my Variable value looks like:

Put all the values together in the New User Variable box:

Press ‘OK’ and you would then see your new Python Path under the ‘User variables’ section. Don’t forget to press ‘OK’ again so that the changes will get implemented.

That’s it! You just added Python to the Windows Path.

You’ll now be able to install Python packages easily, by opening the Windows Command Prompt and then typing:

pip install package name

For example, to install the pandas package, simply type ‘pip install pandas’ and then press Enter:

Similarly, you may upgrade PIP by typing the following command:

Windows path in Python

What is the best way to represent a Windows directory, for example «C:\meshes\as» ? I have been trying to modify a script but it never works because I can’t seem to get the directory right, I assume because of the ‘\’ acting as escape character?

5 Answers 5

you can use always:

this works both in linux and windows. Other posibility is

if you have problems with some names you can also try raw string literals:

however best practice is to use the os.path module functions that always select the correct configuration for your OS:

From python 3.4 you can also use the pathlib module. This is equivelent to the above:

Use the os.path module.

Or use raw strings

I would also recommend no spaces in the path or file names. And you could use double backslashes in your strings.

Yes, \ in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a , which is collapsed into one character that is ASCII Bell:

Other common escape sequences include \t (tab), \n (line feed), \r (carriage return):

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python’s escape sequences is here.

There are a variety of ways to deal with that:

Python on Windows should handle forward slashes, too.

Как добавить 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.

Читайте также:  Как следить за 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.

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

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

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

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

Читайте также:  Взлом wifi linux дистрибутив

В следующем появившемся окне нажмите 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 .

Adding Python Path on Windows 7

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

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.

21 Answers 21

  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.

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\
Оцените статью