You may need to add Python to PATH
if you’ve installed Python, but typing python
on the command line doesn’t seem to work. You may be getting a message saying that the term python
isn’t recognized, or you may end up with the wrong version of Python running.
A common fix for these problems is adding Python to the PATH
environment variable. In this tutorial, you’ll learn how to add Python to PATH
. You’ll also learn about what PATH
is and why PATH
is vital for programs like the command line to be able to find your Python installation.
The steps that you’ll need to take to add something to PATH
will depend significantly on your operating system (OS), so be sure to skip to the relevant section if you’re only interested in this procedure for one OS.
Note that you can use the following steps to add any program to PATH
, not just Python.
How to Add Python to PATH
on Windows
The first step is to locate the directory in which your target Python executable lives. The path to the directory is what you’ll be adding to the PATH
environment variable.
To find the Python executable, you’ll need to look for a file called python.exe
. The Python executable could be in a directory in C:\Python\
or in your AppData\
folder, for instance. If the executable were in AppData\
, then the path would typically look something like this:
In your case, the <USER>
part would be replaced by your currently logged-in user name.
Once you’ve found the executable, make sure it works by double-clicking it and verifying that it starts up a Python REPL in a new window.
If you’re struggling to find the right executable, you can use Windows Explorer’s search feature. The issue with the built-in search is that it’s painfully slow. To perform a super-fast full system search for any file, a great alternative is Everything:
Those paths highlighted in yellow, namely those at \WindowsApps
and \Python310
, would be ideal candidates to add to PATH
because they look like executables at the root level of an installation. Those highlighted in red wouldn’t be suitable because some are part of a virtual environment—you can see venv
in the path—and some are shortcuts or internal Windows installations.
You may also encounter Python executables that are installed within the folder for a different program. This is due to the fact that many applications bundle their own version of Python within them. These bundled Python installations would also be unsuitable.
Once you’ve located your Python executable, open the Start menu and search for the Edit the system environment variables entry, which opens up a System Properties window. In the Advanced tab, click on the button Environment Variables. There you’ll see User and System variables, which you’ll be able to edit:
In the section entitled User Variables, double-click on the entry that says Path. Another window will pop up showing a list of paths. Click the New button and paste the path to your Python executable there. Once that’s inserted, select your newly added path and click the Move Up button until it’s at the top.
That’s it! You may need to reboot your computer for the changes to take effect, but you should now be able to call python
from the command line.
For setting the PATH
environment variable from the command line, check out the section on Configuring Environment Variables in the Windows Python coding setup guide. You can also find instructions in the supplemental materials:
You may also want to set up PATH
on your Linux or macOS machine, or perhaps you’re using Windows Subsystem for Linux (WSL). If so, read the next section for the procedure on UNIX-based systems.
How to Add Python to PATH
on Linux and macOS
Since Python typically comes pre-installed on UNIX-based systems, the most common problem on Linux and macOS is for the wrong python
to run, rather than not finding any python
. That said, in this section, you’ll be troubleshooting not being able to run python
at all.
The first step is locating your target Python executable. It should be a program that you can run by first navigating to the containing directory and then typing ./python
on the command line.
You need to prepend the call to the Python executable with its relative path in the current folder (./
) because otherwise you’ll invoke whichever Python is currently recorded on your PATH
. As you learned earlier, this might not be the Python interpreter that you want to run.
Often the Python executable can be found in the /bin/
folder. But if Python is already in the /bin/
folder, then it’s most likely already on PATH
because /bin/
is automatically added by the system. If this is the case, then you may want to skip to the section on the order of paths within PATH
.
Since you’re probably here because you’ve installed Python but it’s still not being found when you type python
on the command line, though, you’ll want to search for it in another location.
That said, it might be that /bin/
has been removed from PATH
altogether, in which case you might skip forward to the section on mangaging PATH
.
Once you’ve located your Python executable and are sure it’s working, take note of the path for later. Now it’s time to start the process of adding it to your PATH
environment variable.
First, you’ll want to navigate to your home folder to check out what configuration scripts you have available:
You should see a bunch of configuration files that begin with a period (.
). These are colloquially known as dotfiles and are hidden from ls
by default.
One or two dotfiles get executed whenever you log in to your system, another one or two run whenever you start a new command-line session, and most others are used by other applications for configuration settings.
You’re looking for the files that run when you start your system or a new command-line session. They’ll probably have names similar to these:
.profile
.bash_profile
.bash_login
.zprofile
.zlogin
The keywords to look for are profile and login. You should, in theory, only have one of these, but if you have more than one, you may need to read the comments in them to figure out which ones run on login. For example, .profile
file on Ubuntu will typically have the following comment:
So, if you have .profile
but also .bash_profile
, then you’ll want to use .bash_profile
.
You can also use a .bashrc
or .zshrc
file, which are scripts that run whenever you start a new command-line session. Run command (rc) files are common places to put PATH
configurations.
To add the Python path to the beginning of your PATH
environment variable, you’re going to be executing a single command on the command line.
Use the following line, replacing <PATH_TO_PYTHON>
with your actual path to the Python executable, and replace .profile
with the login script for your system:
This command adds export PATH="<PATH_TO_PYTHON>:$PATH"
to the end of .profile
. The command export PATH="<PATH_TO_PYTHON>:$PATH"
prepends <PATH_TO_PYTHON>
to the PATH
environment variable. It’s similar to the following operation in Python:
Since PATH
is just a string separated by colons, prepending a value involves creating a string with the new path, a colon, then the old path. With this string, you set the new value of PATH
.
To refresh your current command-line session, you can run the following command, replacing .profile
with whichever login script you’ve chosen:
Now, you should be able to call python
from the command line directly. The next time you log in, Python should automatically be added to PATH
.
If you’re thinking this process seems a bit opaque, you’re not alone! Read on for more of a deep dive into what’s going on.
Understanding What PATH
Is
PATH
is an environment variable that contains a list of paths to folders. Each path in PATH
is separated by a colon or a semicolon—a colon for UNIX-based systems and a semicolon for Windows. It’s like a Python variable with a long string as its value. The difference is that PATH
is a variable accessible by almost all programs.
Programs like the command line use the PATH
environment variable to find executables. For example, whenever you type the name of a program into the command line, the command line will search various places for the program. One of the places that the command line searches is PATH
.
All the paths in PATH
need to be directories—they shouldn’t be files or executables directly. Programs that use PATH
take each directory in turn and search all the files within it. Subdirectories within directories in PATH
don’t get searched, though. So it’s no good just adding your root path to PATH
!
It’s also important to note that programs that use PATH
typically don’t search for anything except executables. So, you can’t use PATH
as a way to define shortcuts to commonly used files.
Understanding the Importance of Order Within PATH
If you type python
into the command line, the command line will look in each folder in the PATH
environment variable for a python
executable. Once it finds one, it’ll stop searching. This is why you prepend the path to your Python executable to PATH
. Having the newly added path first ensures that your system will find this Python executable.
A common issue is having a failed Python installation on your PATH
. If the corrupted executable is the first one that the command line comes across, then the command line will try and run that and then abort any further searching. The quick fix for this is just adding your new Python directory before the old Python directory, though you’d probably want to clean your system of the bad Python installation too.
Reordering PATH
on Windows is relatively straightforward. You open the GUI control panel and adjust the order using the Move Up and Move Down buttons. If you’re on a UNIX-based operating system, however, the process is more involved. Read on to learn more.
Managing Your PATH
on UNIX-based Systems
Usually, your first task when managing your PATH
is to see what’s in there. To see the value of any environment variable in Linux or macOS, you can use the echo
command:
Note that the $
symbol is used to tell the command line that the following identifier is a variable. The issue with this command is that it just dumps all the paths on one line, separated by colons. So you might want to take advantage of the tr
command to translate colons into newlines:
In this example, you can see that badpython
is present in PATH
. The ideal course of action would be to perform some PATH
archaeology and figure out where it gets added to PATH
, but for now, you just want to remove it by adding something to your login script .
Since PATH
is a shell string, you don’t have access to convenient methods to remove parts of it, like you would if it were a Python list. That said, you can pipe together a few shell commands to achieve something similar:
This command takes the list from the previous command and feeds it into grep
, which, together with the -v
switch, will filter out any lines containing the substring badpython
. Then you can translate the newlines back to colons, and you have a new and valid PATH
string that you use right away to replace your old PATH
string.
Though this can be a handy command, the ideal solution would be to figure out where that bad path gets added. You could try looking at other login scripts or examine specific files in /etc/
. In Ubuntu, for instance, there’s a file called environment
, which typically defines a starting path for the system. In macOS, that might be /etc/paths
. There can also be profile
files and folders in /etc/
that might contain startup scripts.
The main difference between configurations in /etc/
and in your home folder is that what’s in /etc/
is system-wide, while whatever’s in your home folder will be scoped to your user.
It can often involve a bit of archeology to track down where something gets added to your PATH
, though. So, you may want to add a line in your login or rc script that filters out certain entries from PATH
as a quick fix.
Conclusion
In this tutorial, you’ve learned how to add Python, or any other program, to your PATH
environment variable on Windows, Linux, and macOS. You also learned a bit more about what PATH
is and why its internal order is vital to consider. Finally, you also discovered how you might manage your PATH
on a UNIX-based system, seeing as it’s more complex than managing your PATH
on Windows.
Last Updated :
07 Dec, 2023
Python is a great language! However, it doesn’t come pre-installed with Windows. Hence we download it to interpret the Python code that we write. But wait, windows don’t know where you have installed the Python so when trying to any Python code, you will get an error. We will be using Windows 10 and python3 for this article. (Most of the part is the same for any other version of either Windows or Python)
Add Python to Windows Path
Below are the ways by which we can add Python to the Windows path:
Step 1: Locate Python Installation
First, we need to locate where the Python is being installed after downloading it. Press the WINDOWS key and search for “Python”, you will get something like this.
Step 2: Verify Python Installation
If no results appear then Python is not installed on your machine, download it before proceeding further. Click on open file location and you will be in a location where Python is installed, Copy the location path from the top by clicking over it.
Step 3: Add Python to Path as an Environmental Variable
Now, we have to add the above-copied path as a variable so that windows can recognize. Search for “Environmental Variables”, you will see something like this:
Click on that
Now click the “Environmental Variables” button
Step 4: Add Python Path to User Environmental Variables
There will be two categories namely “User” and “System”, we have to add it in Users, click on New button in the User section. Now, add a Variable Name and Path which we copied previously and click OK. That’s it, DONE!
Step 5: Check if the Environment variable is set or not
Now, after adding the Python to the Environment variable, let’s check if the Python is running anywhere in the windows or not. To do this open CMD and type Python. If the environment variable is set then the Python command will run otherwise not.
Related Article – Download PyCham IDE
В процессе работы с различными проектами разработчики часто сталкиваются с необходимостью обеспечения правильной конфигурации их рабочей среды. Настройка окружения, включая добавление программных языков в системные переменные, может стать важным аспектом подготовки к эффективной разработке. Правильная интеграция инструментов и утилит обеспечивает бесперебойное исполнение кода, независимо от операционной системы, будь то Linux или Windows.
Довольно часто встает задача добавления интерпретатора языка программирования в системные параметры, чтобы можно было работать с ним из командной строки. Независимо от того, используете вы Linux или Windows, такая настройка облегчает запуск скриптов и автоматизацию процессов. Задача сводится к простым действиям, но может немного отличаться в зависимости от операционной системы, что требует внимательного подхода и следования ряду важных шагов.
В среде Linux, например, достаточно отредактировать файл конфигурации оболочки. Пример команды для этого:
echo 'export PATH=$PATH:/путь/к/каталогу' >> ~/.bashrc source ~/.bashrc
На Windows же система предложит несколько иной подход, требующий вмешательства в графический интерфейс и редактирование переменных среды через панель управления. Здесь важно следовать инструкции по выбору нужных переменных и аргументов, чтобы избежать ошибок в настройке.
Расширение системных возможностей путем корректировки переменных окружения позволяет сделать работу более гибкой и удобной, независимо от используемой платформы. Прочтите подробное руководство и настройте ваше окружение должным образом, чтобы избежать возможных трудностей в процессе разработки.
Понимание PATH и его значение
Когда мы говорим о PATH, речь идет о неявной указке для операционной системы, которая подсказывает, где находить нужные приложения и скрипты. Эта концепция связана с системной переменной, позволяющей упрощать запуск и управление программами. Осознание значения этой переменной важно для всех, кто работает в командах разработки и сталкивается с необходимостью взаимодействия между различными программными средами.
Переменная PATH используется системами Windows и Linux для определения тех директорий, где нужно искать исполняемые файлы. Если вы неоднократно задавались вопросами об ошибках в командной строке, то скорее всего сталкивались с этой переменной. Она автоматически определяет места нахождения часто используемых команд, значительно упрощая работу с программным обеспечением без необходимости постоянного указания полного пути к программам.
На платформе Windows управлять этой переменной можно через системную панель управления. С другой стороны, пользователи Linux взаимодействуют с ней через текстовые файлы, например, .bashrc
или .profile
. В обоих случаях, процесс установки и настройки понятийно идентичен, но детали варьируются.
Рассмотрим краткие примеры управления переменной PATH в системах Windows и Linux:
Операционная система | Способ изменения |
---|---|
Windows |
Используется системная утилита для настройки окружения. Команда: |
Linux | Редактируется файл конфигурации, например, .bashrc :export PATH=$PATH:/usr/local/newapp |
Правильная настройка и понимание variable PATH экономит время и ресурсы при интеграции и использовании новых программ. Убедитесь в добавлении и хранении правильных путей в этой переменной для ускорения взаимодействия с командной строкой и скриптами без лишнего вмешательства.
Установка Python на компьютере
Windows
В операционной системе Windows установка начинается с загрузки установочного файла с официального сайта. После этого:
- Запустите загруженный инсталлятор.
- В появившемся окне выберите опцию для установки, удостоверившись, что отмечена галочка для добавления в системную переменную.
- Следуйте инструкциям мастера по установке, выбирая необходимые опции.
Теперь для проверки корректности инсталляции откройте командную строку и выполните:
python --version
При успешной установке командная строка должна отобразить версию. Если версия не отображается, проверьте настройки системных переменных.
Linux
Большинство дистрибутивов Linux имеют предустановленную версию интерпретатора, но для установки последней версии потребуется выполнить несколько команд в терминале:
sudo apt update
sudo apt install python3
Эти действия обновят системные пакеты и установят последнюю версию. Проверить корректность установки можно при помощи команды:
python3 --version
Если появится номер версии, установка прошла успешно.
Теперь ваш компьютер готов к работе с интерпретатором, и вы можете насладиться разработкой проектов. Обратите внимание на то, что Process инсталляции может немного варьироваться в зависимости от особенностей операционной системы и используемой версии.
Проверка текущих системных переменных
Прежде чем вносить изменения, важно убедиться в текущем состоянии системных переменных на вашем устройстве. Это поможет избежать ошибок и обеспечит правильную настройку среды. В данном разделе разобраны способы проверки переменных окружения на разных операционных системах, что позволит вам осознанно управлять изменениями.
Для пользователей Windows определить текущие системные переменные не составляет труда. Откройте командную строку, введя cmd в поиске и запустив соответствующее приложение. В открывшемся окне наберите команду:
echo %PATH%
set
На системах, работающих под управлением Linux, используйте терминал для проверки. Выполните следующую команду:
echo $PATH
Результат команды покажет все пути, зарегистрированные в PATH. Если необходимо просмотреть прочие переменные окружения, используйте команду:
printenv
Эти команды дают обширную информацию о текущих настройках среды выполнения. Понимание текущего состояния системных переменных позволит легко управлять и, если нужно, адаптировать их для удовлетворения ваших потребностей. Такие проверки особенно полезны при конфигурации новых инструментов или при устранении неполадок.
Пошаговое добавление Python в PATH
Настройка в Windows
- Перейдите в Этот компьютер и выберите Свойства через контекстное меню.
- Откройте Дополнительные параметры системы и перейдите на вкладку Дополнительно.
- Щелкните Переменные среды.
- В списке Системные переменные найдите строку с именем Path и выберите Изменить.
- Нажмите Создать и введите путь к каталогу, где установлена ваша версия Python, например:
C:\Python39\
. - Нажмите ОК для сохранения изменений.
Настройка в Linux
- Откройте терминал.
- Используйте текстовый редактор, чтобы открыть файл
~/.bashrc
или~/.bash_profile
:nano ~/.bashrc
. - Добавьте в файл следующую строку:
export PATH=$PATH:/usr/local/bin/python3
. - Сохраните изменения, нажав
Ctrl + O
, затемEnter
, и выйдите из редактора с помощьюCtrl + X
. - Примените изменения командой:
source ~/.bashrc
.
Проверка переменных
После установки убедитесь, что новая директория корректно добавлена. Для проверки наберите в командной строке:
python --version
Если команда показывает установленную версию, значит, все сделано верно. Теперь вы можете легко использовать команду в терминале без указания полного пути до исполняемого файла.
Проверка корректности изменений PATH
После модификации системной переменной PATH важно проверить, что изменения выполнены правильно. Это позволяет убедиться, что ваш компьютер распознаёт и без ошибок использует изменённые параметры, и вы сможете эффективно работать с установленными программами.
Первым шагом к проверке обновлённой переменной будет использование командной строки. Откройте консоль в вашей системе Windows. Это можно сделать, введя в строке поиска меню Пуск слово cmd и выбрав соответствующее приложение. После открытия консоли, введите команду:
echo %PATH%
Эта команда покажет текущие значения переменной PATH. Пробегитесь взглядом по списку значений, чтобы убедиться, что необходимый путь был успешно добавлен. Если путь отсутствует, это может свидетельствовать о неправильном процессе добавления.
Ещё одним способом проверки является запуск необходимой программы из консоли без указания полного пути к файлу. Введите в командной строке название программы и нажмите Enter. Если программа запускается без ошибок, это значит, что системная переменная настроена корректно и все необходимые изменения были успешно применены.
Для дополнительной проверки вызываемых команд или сценариев на корректность выполненной операции, попробуйте дополнительно использовать отладочную информацию или встроенные функции диагностики самого Microsoft Windows, которые могут указать на возможные проблемы в конфигурации переменных.
Рекомендуется перезапустить систему после изменения системных переменных, чтобы изменения гарантированно вступили в силу во всех приложениях и сессиях. Таким образом, можно добиться уверенности, что изменения PATH применены успешно и корректно работают в любом контексте работы с файлами и программами.
Устранение возможных ошибок и проблем
Настройка переменных окружения может иногда вызывать различные затруднения, особенно у начинающих пользователей. Ошибки могут возникать по ряду причин: вследствие неправильно заданных параметров, путей к директориям или нарушений в системных настройках.
Одной из частых ошибок является опечатка в строке переменных. Например, если неверно указать путь до исполняемого файла, система не сможет его обнаружить. Важно удостовериться, что вы используете правильный синтаксис. На операционных системах на основе UNIX (таких как Linux) дополнительно проверяйте учет регистра, так как он имеет значение.
Некоторые пользователи могут столкнуться с проблемами, связанными с конфликтами между версиями. Проверьте, что путь указывает именно на ту версию, которая вам необходима. Для этого можно использовать команду which
в терминале Linux, чтобы увидеть путь к текущей версии.
На Windows ошибки могут возникнуть, если значения переменных были изменены неадекватно. В этом случае вам может понадобиться открыть Редактор системных переменных и восстановить значение переменной вручную. Просто убедитесь, что все пути корректны и там нет лишних пробелов.
Еще одна возможная проблема – операционная система не обновляет переменные окружения после изменений. Перезагрузите компьютер или завершите сеанс пользователя, чтобы удостовериться, что обновления вступили в силу.
Продвинутое устранение неполадок может включать отладку скриптом. Напишите небольшой скрипт на языке программирования, который вы используете, чтобы вывести значение переменных окружения и убедиться, что они изменены правильно. Например, на Python это можно сделать с помощью:
import os print(os.environ['PATH'])
Если вы проверили все возможные источники ошибок, но проблема осталась нерешенной, возможно, стоит обратиться к документации вашей операционной системы или к сообществу пользователей на форумах.
Комментарии
When running Python for the first time after the installation, the command may return an error or start a Python version different from the one you installed. The solution is to add the correct Python binary to the PATH variable.
In this article, learn how to add the Python binary to PATH on Windows, Linux, and macOS.
Prerequisites
- Python installed.
- Command-line access to the system.
What Is PATH?
PATH is a system variable that contains a list of directories in which the operating system looks for applications. The PATH value is a string of directories separated by colons (on Linux and macOS) or semicolons (on Windows). Below is an example of a PATH variable in Ubuntu:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
When a user types a terminal command without providing a command path, the system searches for the corresponding binary in the PATH directories. If the binary is in any of the directories, the system executes it.
How to Add Python to PATH on Windows
Use Windows System Properties to add Python’s installation directory to the PATH variable. The steps below show how to perform this action using the GUI.
Step 1: Find Python Installation Directory
Before modifying the PATH variable, find the Python installation directory. By default, Python is in the Python[version-number] directory located at:
C:\Users\[username]\AppData\Local\Programs\Python
Note: AppData is a hidden directory. To access it, enable the Show Hidden Files option in File Explorer.
Follow the steps below to find and copy the directory address:
1. Open File Explorer.
2. Navigate to the Python directory.
3. Right-click the directory in the navigation bar.
4. Select Copy address as text.
Step 2: Locate PATH Variable Options
The options to modify the contents of the PATH variable are in the Environment Variables section of Windows System Properties. To access the options:
1. Click the Start button.
2. Search for and select Edit the system environment variables.
3. Select the Advanced tab in the System Properties window.
4. Click the Environment Variables button in the section’s bottom-right corner.
5. Access the PATH options by double-clicking the Path item in the User variables section of the Environment variables window.
Step 3: Add Python Directory to PATH
The Edit environment variable window contains a list of directories previously added to PATH. To add the Python entry:
1. Select the New button in the upper-right corner. A new blank entry appears in the list.
2. Paste the address from Step 1 into the entry and press Enter.
3. Move the address to the top of the list by pressing the Move Up button.
4. Click OK to exit.
5. Ensure the PATH variable now contains the Python directory by using the echo command in PowerShell:
echo $env:path
The output shows that PATH contains the Python directory.
Note: If you use Command Prompt, view PATH with the echo %PATH%
command.
How to Add Python to PATH on Linux and Mac
Due to the fundamental design similarities between the two systems, the procedure for appending the Python directory to PATH on Linux and macOS is the same. Edit the PATH variable by executing the steps below.
Step 1: Add Path
The export command allows you to change environmental variables such as PATH. However, the changes last only for the duration of the current terminal session.
To make changes permanent, add the export command to the .profile file using the syntax below:
echo export PATH="[python-path]:$PATH" >> ~/.profile
For example, the following command permanently adds the /home/marko/.localpython/bin directory to PATH:
echo export PATH="/home/marko/.localpython/bin:$PATH" >> ~/.profile
Step 2: Apply Changes
The operating system reads .profile on system startup. Restart the system for the changes to take effect. Alternatively, force the system to read .profile with the command below:
source ~/.profile
The command produces no output.
Step 3: View PATH in Linux and macOS
Confirm that the path to the Python binary has been added to the PATH variable by typing:
echo $PATH
The new directory appears first in the string.
Order Within PATH
As previously mentioned, when a user types a terminal command, the system checks the PATH variable and searches the listed directories for the binary of the same name. However, it is important to mention that the system reads the directories from first to last and stops searching as soon as it finds the first matching binary.
Prepending the PATH variable with the directory containing the desired Python version ensures that the system reads it first and executes the correct binary. It is considered best practice, especially if you have more than one Python version installed on your system.
Placing the correct directory first in PATH makes the system ignore other Python installations, but they will still be part of the variable and may make it difficult to read. If there are Python installations on your PATH that you want to remove, refer to the sections below.
Managing PATH on Windows
Edit and remove PATH variable addresses in Windows from the Edit environment variable window mentioned in Step 3 of the How to Add Python to PATH on Windows section. To remove an address, select it and click the Delete button on the right side of the window.
Use the Edit button to change the saved address and the Move Up and Move Down buttons to change the order of addresses within the PATH variable.
Managing PATH on Linux or Mac
Since PATH management on Linux and macOS is done using CLI, the procedure for editing and deleting PATH directories is slightly more complicated than on Windows. Follow the steps below to learn how to edit PATH on Linux and macOS.
1. View a tidy list of the directories that are part of the PATH variable by typing:
echo $PATH | tr ":" "\n"
The tr command takes the input from echo and replaces each colon with a new line, creating a more legible list of directories.
2. Remove a directory from a path by using the following command:
export PATH=`echo $PATH | tr ":" "\n" | grep -v '[path-to-remove]' | tr "\n" ":"`
The command performs the following operations:
- The tr command formats the echo output and passes it to the grep command.
- When used with the -v option, grep removes the line containing the [path-to-remove] and passes the output back to tr.
- tr reformats the output into a colon-separated string and assigns it as the value of the PATH variable.
Note: The method above only removes the path for the duration of the terminal session. To permanently remove an unneeded path, locate the file that exports it to PATH and remove the export line. Files that may contain the export command are .bashrc .zshrc, .bash_profile, .zprofile, .profile, and similar configuration files.
Conclusion
After reading this article, you should know how to add a directory containing a Python binary to the PATH variable and run Python without specifying its path. The article also explained how to edit and remove items from the PATH variable.
If you are new to Python, read our Python Data Types overview.
Was this article helpful?
YesNo
Table of contents
- How To Add Python To The System Path?
- How To Avoid ‘Command Not Recognized’ Errors in Windows Command Prompt?
- Why Add Python to PATH?
- Steps For Adding Python To Path In Windows
- Steps For Adding Python To Path In Mac
- Wrapping up
- FAQs
Adding Python to the system’s PATH is an essential step when working with Python, as it allows you to run Python scripts and access Python packages from any directory in the command prompt or terminal.
By adding Python to the PATH, you eliminate the need to specify the full path to the Python executable every time you want to use it.
This blog will walk you through adding Python to PATH on Windows, macOS, and Linux.
With step-by-step instructions and screenshots on how to add python path to environment variables, we’ll make it effortless for you to integrate Python into your development workflow.
By the end, you’ll be ready to start using Python from the command line without having to navigate to its installation directory every time.
How To Add Python To The System Path?
Every Operating System has a list of directories containing the executable files for the commands and one executable file for each command. The name of the command itself saves each executable file. This list of directories is stored in a variable called Path.
Here’s a step-by-step guide on how to add Python to the system path:
1. Find Python Installation Directory
First, locate where Python is installed on your computer. This varies depending on your operating system. For example:
Windows: Typically installed in C:PythonXX (where XX is the version number).
macOS: Usually found in /Library/Frameworks/Python.framework/Versions/XX.X/.
Linux: Commonly located in /usr/bin/pythonX.X/.
2. Access System Environment Variables
Windows: Right-click on “This PC” or “My Computer,” choose “Properties,” then click on “Advanced system settings.” In the “System Properties” window, click on “Environment Variables.”
macOS and Linux: Open a terminal window.
3. Locate The “Path” Variable
In the “Environment Variables” window (Windows) or terminal (macOS/Linux), find the “Path” variable under the “System variables” section.
4. Edit The “Path” Variable
Windows: Select the “Path” variable and click “Edit.” Then click “New” and add the path to your Python installation directory. Click “OK” to save.
macOS and Linux:
– Use a text editor like Nano to open the system environment file.
– Add export PATH=”/path/to/python:$PATH” at the end, replacing /path/to/Python with your Python installation path.
– Save and exit the editor.
Learn more about variables with our blog on Global Variables in Python
5. Apply Changes
Close the terminal or “Environment Variables” window to save the changes.
6. Verify Python Path
Open a new terminal or command prompt window and type ‘Python–version’. The installed version number will be displayed if Python is successfully added to the path.
After completing these steps, Python will be added to the system path, allowing you to run Python commands from any directory without specifying the full path. This means you can easily access Python commands without navigating to the Python installation directory each time.
Learn the ins and outs of Python lists in “Python List : All You Need To Know About Python List“.
How To Avoid ‘Command Not Recognized’ Errors in Windows Command Prompt?
When you type a command in the Command Prompt on Windows, the system tries to find an executable file for that command within the directories listed in the Path variable.
It shows an error message saying the command isn’t recognized if it can’t find the executable. For instance, if you try to run Python and Python isn’t in the Path, you’ll get an error like this:
You can avoid this error by providing the full directory path to the Python executable each time you want to use it. For example:
C:PythonXXpython.exe script.py
But that’s cumbersome and prone to mistakes.
A more convenient solution is to add the directory containing the Python executable to the Path variable.
For example, if Python is installed in C:PythonXX, you can add C:PythonXX to the Path variable. Then, you can simply type Python in the Command Prompt from any directory, and it will work without errors.
Why Add Python to PATH?
When Python is added to the PATH, it becomes a globally accessible command, regardless of your current working directory.
This means that you can run Python scripts or interact with the Python interpreter from any location in the command prompt or terminal, without having to navigate to the Python installation directory every time.
Moreover, by adding Python to the PATH, you can easily install and manage Python packages using tools like pip, as they rely on the Python executable being in the PATH.
Adding Python to the PATH streamlines your Python development workflow and allows for a smoother coding experience.
Discover the building blocks of Python programming!
Enroll in Free Python Fundamentals for Beginners course and gain essential skills to excel in programming.
Steps For Adding Python To Path In Windows
To add python to the windows path, follow these steps:
Step 1:
Click on ‘This PC’
Step 2:
Go to ‘Properties’ on the menu bar
Step 3:
Choose the ‘Advanced Settings’ option given on the left hand side as shown in the figure below:
Step 4:
Now, click on the button ‘Environment Variables’ on the bottom right. An environment Variables window will open up as seen in the figure below:
Step 5:
You will find a ‘System variables’ section on the lower part of the ‘Environment Variables’ window. Choose the ‘Path’ variable from the given list of variables and click on the ‘Edit’ button to add Python to environment variables. Take a look at the figure below for reference.
Step 6:
An ‘Edit environment variable’ window will pop up as shown in the figure given below. This window shows you the list of directories that the Path variable currently contains. Click on ‘New’ button given on the right hand side of the window.
Step 7:
Write down the location of the Python’s install directory as shown below and click on ‘OK’.
And Bingo! You have successfully added Python to the Path using the steps outlined above on how to set Python path in Windows.
You can check if it has been added properly by writing the Python command in your command line. You will not get the same error as before.
Instead, the following message will be displayed on the screen. This ensures that Python has been successfully installed and added to the Path variable on your system.
Steps For Adding Python To Path In Mac
Like the Command Prompt of Windows, you have the Terminal in Mac. When the installed Python is not added to the Path variable, and you write the ‘python’ command in the Terminal, an error is raised with a message stating that the Command is not found.
Hence, to add Python to the Path variable on Mac, follow through the given steps on how to add Python to path Mac.
Step 1:
Open the Terminal on your MAC and give the following command:
sudo nano /etc/paths
The terminal will prompt you to enter your password.
Step 2:
Enter your password. This will open up a list of directories that are stored in the Path variable.
Step 3:
Now, after the last directory location, enter the path to the Python Install directory.
Step 4:
Press Ctrl + X to quit and further, press Y to save the changes to the Path variable. This will now allow you to access python directly from the terminal without being required to enter its full location.
Now, if you type in the command ‘python’ in the Terminal, no error will be raised. Instead, a the installed python version will be displayed, as shown in the figure below, which will confirm that Python has been successfully added to the Path.
Adding Python to the system’s PATH is a crucial step for any Python developer or enthusiast. It simplifies the process of running Python scripts and accessing Python packages from any directory in the command prompt or terminal.
In this blog post, we covered the steps to add Python to the PATH on three major operating systems: Windows, macOS, and Linux. We provided detailed instructions, accompanied by screenshots, to make it easy for readers to follow along.
For Windows users, we explained how to check if Python is already installed, how to add Python to the PATH on Windows 10/8/7, and how to verify the PATH configuration.
On macOS, we outlined the process of checking Python installation, adding Python to the PATH, and verifying the configuration. And for Linux users, we covered checking Python installation, adding Python to the PATH, and verifying the configuration.
By adding Python to the PATH, developers can save time and effort by eliminating the need to specify the full path to the Python executable every time they want to use it. It enhances productivity and makes Python development more efficient.
Wrapping up
Incorporating Python into your system’s PATH is a straightforward yet impactful measure that can significantly amplify your Python development journey. It empowers you to seamlessly engage with Python and leverage its capabilities from any directory.
By adhering to the guidelines outlined in this discussion, you can effortlessly integrate Python into the PATH on your chosen operating system, enhancing your Python projects’ efficiency and accessibility. Hopefully, you now have a more precise grasp of this concept.
If you’re keen on delving deeper into Python and exploring its applications in Data Science, Machine Learning, and Artificial Intelligence, Great Learning Academy offers free courses with certificate tailored to these domains.
FAQs
Can I add multiple Python versions to the system path?
Yes, you can add multiple Python versions to the system path by specifying the paths to each Python executable in the PATH environment variable, separated by a colon (:) on Unix-like systems or a semicolon (;) on Windows.
Do I need administrative privileges to add Python to the system path?
You may require administrative privileges to modify the system PATH variable on Windows. However, you can add Python to the user-specific PATH variable without administrative privileges. You can modify the user-specific PATH variable on macOS and Linux without administrative privileges.
How do I verify if Python is successfully added to the system path?
You can verify if Python has been successfully added to the system path by opening a new command prompt or terminal window and typing Python or Python-version. If Python is correctly added to the path, it should display the Python interpreter version without errors.
Can I remove Python from the system path if needed?
Yes, you can remove the Python add to path from the system path by editing the appropriate shell configuration file and removing the corresponding path entry. Alternatively, you can uninstall Python and choose not to add it to the system path during reinstallation.
Does adding Python to the system path affect virtual environments?
Adding Python to the system path does not inherently affect virtual environments. Virtual environments operate independently of the system path, allowing you to manage Python dependencies and project-specific configurations separately.