How to add python to path windows
Как добавить Python в переменную PATH Windows
Запуск Python с терминала часто бывает неизбежен. Однако, если вы впервые установили Python в Windows 10, запуск его через Терминал Windows возможен только в том случае, если он добавлен в переменную среды Windows PATH.
Это может показаться сложным, но бояться нечего. Чтобы помочь вам преодолеть сложности, связанные с добавлением Python в PATH Windows после его установки, давайте рассмотрим варианты и несколько необходимых шагов.
Зачем добавлять Python в Windows PATH?
Если вам не удалось добавить Python в PATH в вашей ОС Windows, вы не сможете запустить интерпретатор Python, запустить виртуальную среду программирования или выполнить такие команды, как pip install, из терминала.
Это потому, что, когда вы запускаете любую программу, отличную от стандартной, из командной строки, машина ищет исполняемый файл в текущей папке или в ПУТИ Windows.
Как вручную добавить Python в Windows PATH
Во-первых, если вы не установили Python на свой компьютер, перейдите на веб- сайт python.org, чтобы загрузить и установить предпочитаемую версию.
Чтобы запускать программы Python из командной строки, выполните шаги, выделенные ниже.
Найдите путь установки Python на вашем ПК
Далее: Добавить Python в PATH в пользовательских переменных
Вернитесь в папку пути установки Python и дважды щелкните Scripts, чтобы открыть этот каталог. Затем скопируйте его путь из панели пути в верхней части окон (помимо панели поиска), как вы это делали ранее для пути установки Python.
Добавление Python в PATH с помощью параметра системных переменных
Добавить Python в Windows PATH автоматически
Вы также можете автоматически добавить Python в PATH Windows во время установки. Хотя этот метод работает не во всех случаях, вы все равно можете попробовать.
Установка этого флажка автоматически добавляет Python в ваш путь к Windows. Это означает, что вы можете запускать команды Python через командную строку сразу после установки.
Подтвердите, что Python добавлен в Windows PATH
Однако, чтобы проверить, добавили ли вы каталог Scripts в Windows PATH, попробуйте запустить пакет установки pip на терминале, заменив «package» на предпочитаемую вами библиотеку. Если вы установили Python 2.7.9 и выше, команда устанавливает названный пакет, указывая, что вы также успешно добавили скрипты Python в путь.
Другая программа, которую вам следует подумать о добавлении в путь к Windows
Помимо добавления Python в Windows PATH, вы можете добавить текстовые редакторы, интегрированные среды разработки (IDE), Git, Node, Anaconda и многие другие программы.
How do I add Python to the Windows PATH?
I want to be able to run Python commands from the Windows CMD. However, if I don’t specify Python’s full path for each command, I get an error saying «Python is not recognized as an internal or external command, operable program or batch file.«
How do I add Python to the Windows PATH permanently?
5 Answers 5
For Windows 10/8/7:
Add Python’s path to the end of the list (the paths are separated by semicolons). For example:
For Windows XP:
Add Python’s path to the end of the list (the paths are separated by semicolons). For example:
Test on a new terminal window or if using an integrated terminal within a text editor, close and restart your editor or the changes won’t be applied.
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.
Windows has a built-in dialog for changing environment variables (following guide applies to XP classical view): Right-click the icon for your machine (usually located on your Desktop and called “My Computer”) and choose Properties there. Then, open the Advanced tab and click the Environment Variables button.
In short, your path is:
My Computer ‣ Properties ‣ Advanced ‣ Environment Variables In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted access to your machine (i.e. Administrator rights).
Right-click on My Computer, choose Properties. Then find the Environment Variables button (on Win7, it’s under the Advanced tab; I forget where it is on other versions of Windows). Click that, and under System variables, edit the Path one.
Not the answer you’re looking for? Browse other questions tagged windows python path or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.9.39043
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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)
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:
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:
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:
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:
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.
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:
and here is how (plagiating my own answer to my own question on the very same topic):
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:
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:
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:
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:
Самая лучшая практика: работа с path в Python
Все та же проблема: список папок и дисков
В последней статье мы использовали рекурсивную функцию размером менее 10 строк для решения проблемы сканирования папок и ранжирования файлов по дате изменения и размеру.
Теперь я подниму планку и покажу, как можно было сделать лучше.
Объединяем пути с помощью Pathlib
Старые идеи в новом обличье?
Предыдущее решение с соединением путей выглядело следующим образом:
Преимущество такого подхода заключается в том, что решение не зависит от операционной системы, и вам не нужно складывать строки с помощью оператора «+» или форматирования.
Тем не менее, здесь можно допустить ошибку, например, непреднамеренно или ошибочно определить путь к каталогу с помощью закрывающего разделителя.
Несмотря на то, что в этом примере показан рабочий код, неправильный разделитель приведет к ошибке при вызове этого пути. И такие ошибки могут возникать всякий раз, когда далекие от кода пользователи оперируют путями в конфигурационных файлах, не обращая внимания на соглашения.
Напомню, старый вариант выглядел вот так:
А вот альтернативный:
Оба варианта дают один и тот же результат. Так чем же второй вариант лучше?
Объектно-ориентированный и более устойчивый к ошибкам
Однако пример с операторами перегрузки в данном случае более интересен:
Сначала разделение на два пути кажется недопустимым. Однако объект path был перегружен так, чтобы работать как объединенный путь.
В дополнение к этому синтаксическому сахару объекты path будут перехватывать другие типичные ошибки:
Обработка пути с помощью os.walk
В своей последней статье я использовал os.listdir , os.path.isdir и рекурсивную функцию для итерации по дереву путей и разграничения файлов и папок.
Но os.walk предлагает решение получше. Этот метод создает не список, а итератор, который можно вызывать построчно. В результате мы получим соответствующий путь к папке и список всех файлов по этому пути. Весь процесс происходит рекурсивно, поэтому вы получите все файлы одним вызовом.
Лучшее решение с os.walk и Pathlib
Если вы объедините два вышеупомянутых метода, то получите решение, которое будет более простым, полностью независимым от операционной системы, устойчивым к неправильным форматам путей и без явных рекурсий:
Если вам удастся улучшить этот вариант, не постесняйтесь рассказать мне об этом. Я был бы рад вашим отзывам!
Первую часть статьи можно найти здесь.
Также приглашаем всех желающих принять участие в бесплатном демо-уроке курса на тему «Три кита: map(), filter() и zip()».
Можно ли писать код, требующий циклов, но без циклов? Может ли он быть быстрее, чем, если бы мы использовали циклы в Python? Для реализации задуманного понадобится знание слов «callback», «iterator» и «lambda». Если интересно — присоединяйтесь!