How to set python to path
How to set python to path
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.
Как добавить Python в переменную Windows PATH
Запуск Python с терминала зачастую неизбежен. Однако, если вы впервые установили Python в Windows 10, запуск его через Терминал Windows возможен только в том случае, если он добавлен в переменную среды Windows PATH.
Это может показаться сложным, но бояться нечего. Чтобы помочь вам преодолеть повороты, связанные с добавлением Python в PATH Windows после его установки, давайте рассмотрим варианты и несколько необходимых шагов.
Зачем Добавлять Python В Windows PATH?
Если вам не удалось добавить Python в PATH в вашей ОС Windows, вы не сможете запустить интерпретатор Python, запустить виртуальную среду программирования или выполнить такие команды, как pip install, из терминала.
Мы исследуем лучшие способы создания виртуальных сред Python и управления ими.
Это потому, что, когда вы запускаете любую программу, отличную от программы по умолчанию, из командной строки, машина ищет исполняемый файл в текущей папке или в ПУТИ Windows.
Как Вручную Добавить 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 + С. Затем перейдите к следующим шагам ниже.
Далее: Добавить 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. Кликните эту переменную и кликните Изменить.
В следующем появившемся окне нажмите 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.
How to add Python to Windows PATH
There are few ways to add Python to Windows PATH. In this guide, you’ll see two methods to add Python to Windows path:
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 at the bottom of the setup screen:
Add Python to PATH
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 the previous version of Python, you may apply the steps below to manually add Python to Windows path.
First, navigate to the Windows Environment Variables screen (where you can add/edit your paths):
That should take you to the Environment Variables screen, where you can add/edit your paths.
Under the User variables box, click on ‘New…‘ to add the ‘Path’ variable (note that if your ‘Path’ variable already exists, then click on ‘Edit…’ instead):
New… Edit…
You should then see the New User Variable box, where you may 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:
(1) The Python application path, which is the folder where you originally installed Python. You can find the Python application path by following these steps:
Here is an example of a Python application path:
(2) The Python Scripts path. The Scripts folder should be located within the Python application path. Example:
After you obtained the paths, fill the New User Variable box that you saw earlier:
For our example:
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.
System variables
…
…
…
OK Cancel
You just added Python to the Windows Path.
You should be able to install Python packages easily, by opening the Windows Command Prompt and then typing:
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:
How to Set Default Path for Python in Windows
If you are a beginner, then this article is for you. As a beginner, you might face problems in setting a proper path for python. In today’s tutorial, we will learn how to set a default path for python whenever we install python into our system.
Introduction
Unlike most operating systems such as Unix, Windows does not include a system-supported installation of Python. To run Python conveniently from a command prompt, you might consider changing some default environment variables in Windows. To temporarily set environment variables, open Command Prompt and use the set command:
Why to set up a path for python?
If you’ve installed Python in Windows using the default installation options, then the path to Python will not be added to the Windows Path variable. The Path variable lists the directories that will be searched for executing when you type a command in the command prompt. By adding the path to the Python executable, you will be able to access python.exe just by typing the python keyword in your command prompt. You will not need to specify the full path to the program.
Let us see what happens if we enter the python command in the command prompt and the path to that executable is not added to the Path variable:
As you can see from the above output, the command was not found. Therefore, to run python.exe, you will need to specify the full path to the executable.
How to select default path while installing python?
There is an easy way to set up the default path during installing the Python. Every python installer comes with an option to add a python path into environmental variables. This will ensure that you can run python from your terminal. To do this –
This way you can set up a default path without any headache. If you already have python installed and do not want to reinstall it, then move on to the next methods.
How to set up a default python path for Windows manually?
To permanently modify the default environment variables : My Computer > Properties > Advanced System Settings > Environment Variables > Edit
Steps to follow in detail.
Before you type any values, you’ll need to locate the relevant Python paths. The paths that you’ll need to get are:
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 a semicolon.
Now select OK
Using python from Command Prompt
Checking of python path
How to handle multiple paths in python?
You may have two versions of python installed in windows in your system, let’s say 2.7 and 3.9. You want to run one of your projects in the python 2.7 version and another project in the 3.9 version. So the problem that lands up here is how you can specify which version you want to use for a specific python project?
So, today I will show you 2 methods of how to manage multiple python paths in windows?
Method 1: By defining the path of the versions
Whenever you try to run Python in the command prompt, it searches the %PATH% environment variable and checks for an executable file which can either be a batch file (.bat), command file (.exe), or any other executable file (.exe) that matches the name given. Once the correct file is found, it executes the program using that file. Now, if you have two versions of Python installed on your system (Python 2.7 and 3.9), then the path variable will contain the location of both the directories. But, there is a problem. The problem is once Windows finds the first match, it will stop examining any other path.
To overcome this problem, you have to call one or both applications using their path explicitly. For example, as you can see below, I have two versions of Python installed on my system.
This method is one of the simplest method for managing multiple paths of python.
Method 2: Creating a shortcut
If you want to avoid using the entire path, create a shortcut for each python.exe file and rename it as python27 and python39.
In order to create the shortcuts, follow the given steps:
To run a file in python 2.7
Also, Check Out Editors Choice:
Conclusion
I hope this article helps you in setting a proper path for python in Windows operating system. As a beginner, you might face difficulties, but no worries, keep reading our tutorials on python and being a pro. Drop a comment if you have doubts. We are just one reply away. Till then, keep reading.
Python is available on a wide variety of platforms including Linux and Mac OS X. Let’s understand how to set up our Python environment.
Local Environment Setup
Open a terminal window and type «python» to find out if it is already installed and which version is installed.
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/
You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats.
Installing Python
Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.
Here is a quick overview of installing Python on various platforms −
Unix and Linux Installation
Here are the simple steps to install Python on Unix/Linux machine.
Follow the link to download zipped source code available for Unix/Linux.
Download and extract files.
Editing the Modules/Setup file if you want to customize some options.
This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.
Windows Installation
Here are the steps to install Python on Windows machine.
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install.
To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done.
Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS’s before Mac OS X 10.3 (released in 2003), MacPython is available.
Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/
jack/macpython.html. You can find complete installation details for Mac OS installation.
Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.
The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.
Setting path at Unix/Linux
To add the Python directory to the path for a particular session in Unix −
In the csh shell − type setenv PATH «$PATH:/usr/local/bin/python» and press Enter.
In the bash shell (Linux) − type export PATH=»$PATH:/usr/local/bin/python» and press Enter.
In the sh or ksh shell − type PATH=»$PATH:/usr/local/bin/python» and press Enter.
Note − /usr/local/bin/python is the path of the Python directory
Setting path at Windows
To add the Python directory to the path for a particular session in Windows −
At the command prompt − type path %path%;C:\Python and press Enter.
Note − C:\Python is the path of the Python directory
Python Environment Variables
Here are important environment variables, which can be recognized by Python −
Sr.No. | Variable & Description | ||
---|---|---|---|
1 |
Sr.No. | Option & Description |
---|---|
1 |