В процессе работы с различными проектами разработчики часто сталкиваются с необходимостью обеспечения правильной конфигурации их рабочей среды. Настройка окружения, включая добавление программных языков в системные переменные, может стать важным аспектом подготовки к эффективной разработке. Правильная интеграция инструментов и утилит обеспечивает бесперебойное исполнение кода, независимо от операционной системы, будь то 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'])
Если вы проверили все возможные источники ошибок, но проблема осталась нерешенной, возможно, стоит обратиться к документации вашей операционной системы или к сообществу пользователей на форумах.
Комментарии
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
Пройдите тест, узнайте какой профессии подходите
Работать самостоятельно и не зависеть от других
Работать в команде и рассчитывать на помощь коллег
Организовывать и контролировать процесс работы
Быстрый ответ
Для Unix/Linux/Mac:
Для Python версии 2.x:
Для Windows:
В Python скрипте или интерактивном режиме:
Вышеуказанные команды позволяют определить путь к исполняемому файлу Python. sys.executable
возвращает полный путь в любом Python-окружении.

Подробные возможности с помощью модуля sys
Модуль sys раскрывает и другую важную информацию:
- sys.exec_prefix указывает путь к папке со стандартными библиотеками Python.
- sys.path выводит список каталогов, где Python ищет модули.
Пример кода:
Заметка: если исполняемый файл Python не добавлен в системный PATH
, команды типа which
или where
могут не работать.
Управление несколькими версиями Python
Если у вас установлено несколько версий Python и используются виртуальные окружения, поиск может усложниться. Для облегчения задачи применяются следующие команды:
Для Unix/Linux/Mac:
Эта команда выведет все пути к исполняемым файлам python3
.
Для Windows: в PowerShell:
В виртуальных окружениях сначала активируйте их, затем команда sys.executable
покажет точный путь:
Типичные проблемы при поиске установки Python
Вы можете столкнуться с такими неприятностями:
- Python 2 против Python 3: Может быть получен путь к неподходящей версии, если обе версии установлены.
- Различия командных оболочек: Установки
PATH
в разных оболочках могут влиять на результаты командwhich
илиwhere
. - Символические ссылки: Временами
which
возвращает путь к символической ссылке, а не к реальному файлу установки.
Визуализация
Представьте себя детективом (🕵️♂️), ищущим скрытого Python:
Каждый инструмент с отличающейся точностью указывает на местоположение Python, где бы он ни прятался.
Уровень эксперта: Раскрытие Python
Вот ещё команды, позволяющие раскрыть установленные версии Python:
Поиск абсолютного пути Pythonistic
Для пользователей Unix readlink поможет определить реальное расположение исполняемого файла Python:
Python и ваша оболочка
У пользователям Bash могут быть интересны команды, связанные с историей использования Python:
P.S.: Это как отправиться на поиски сокровищ в собственном терминале — кто знает, что можно обнаружить!
Переменные окружения под лупой
Переменные окружения, как PATH
, PYTHONHOME
и PYTHONPATH
, могут предоставить дополнительную информацию:
Полезные материалы
- sys — Системно-зависимые параметры и функции – официальная документация Python.
- os — Работа с операционной системой – официальная документация Python.
- Github Gist: Python – inspect – Получение пути вызова – скрипт для вывода обширной информации о путях Python.
- Super User: Добавляем Python в системный путь Windows – инструкция по добавлению Python в системные переменные Windows.
- Работа с файлами в Python – Real Python – обучающий материал по использованию файлов в Python.
- Reddit – Погружение в различные темы – обсуждение по поиску путей Python.
Python is a versatile and widely used programming language, known for its simplicity and easy-to-understand syntax. When you’re setting up a Python development environment, one of the first tasks is locating where Python is installed on your machine. This information is crucial for configuring different tools and managing libraries and environments.
Python is normally installed in the system’s default program files directory. On Windows, it’s typically found in the “C:\PythonXX” folder. On Linux or Mac, it’s often in “/usr/local/bin/pythonX.X”. You can check your Python installation path by running “python –version” or “which python” in the command line.
This article will help you understand how to find the Python installation location on your system, focusing on different methods and operating systems. This knowledge will assist you in setting up your programming environment correctly and provide a better understanding of how Python interacts with your machine.
Let’s get into it!
Python Installation Locations
On various operating systems like Windows, macOS, or Linux, Python’s installation location can vary due to user preferences or installation packages from different sources.
In this section, we’ll look at the installation location of Python for different operating systems. Specifically, we’ll look at the following:
- Python Installation location on Windows
- Python Installation location on MacOS
- Python Installation location on Linux
1. Python Installation Location on Windows
By default, Python installations on Windows are located in the C:\ directory or C:\Users\<User>\AppData\Local\Programs.
The common installation paths for both 32-bit and 64-bit versions may reside in the C:\PythonXX folder, where XX stands for the Python version (e.g., C:\Python27 for Python 2.7).
In newer installations, the 64-bit version is often located in the C:\Program Files\PythonXX folder, while the 32-bit version is in the C:\Program Files (x86)\PythonXX folder.
To find the exact location of your Python installation on Windows, you can use the command prompt by typing where python and press Enter. This command will display the file paths of any installed Python versions on your system.
The following image demonstrates this prompt:
2. Python Installation Location on MacOS
On macOS, Python is typically installed in the /Library/Frameworks/Python.framework/Versions directory, with different versions contained in their respective subfolders (e.g., /Library/Frameworks/Python.framework/Versions/3.9 for Python 3.9).
Alternatively, Python installations managed by Homebrew are located in /usr/local/Cellar/python.
To check the exact path of your Python installation, you can open the terminal and type which python or which python3. Pressing “Enter” will display the file path of the active Python version on your system.
3. Python Installation Location on Linux
In most Linux distributions, Python is installed by default and can be found in the /usr/bin/ directory. The installed versions usually include both Python 2 and Python 3.
For Python 2.x, the executable is named python, while for Python 3.x, it’s named python3.
For systems with multiple Python installations or custom installation paths, you can find the location by typing which python or which python3 in the terminal and pressing Enter.
The command will show the file path of the active Python version on your system.
In the next section, we’ll go over how you can use built-in Python modules to locate the Python folder in your system.
How to Use Python’s os and sys Modules to Locate Python Folder
Python’s os and sys modules are built-in modules that allow you to interact with the operating system.
To locate where Python is installed, follow the steps given below:
- Run Python interpreter by typing python in the terminal or command prompt.
- Execute the following commands:
import os
import sys
print(os.path.dirname(sys.executable))
This Python script is used to print the directory of the Python interpreter being used to execute the script. os.path.dirname(sys.executable) gets the path of the currently running Python interpreter.
The output is given below:
How to Check the Location of Python Executables
When you are working in Python, you’ll want to install libraries from time to time. In most cases, you might want to check the path of a certain library.
You can check the path of a Python library or executable with the pip package manager. To do this, open up CMD and run the following code:
pip show <package name>
Let’s say I want to check the location of NumPy library on my operating system. To do this, I’ll type the following prompt in CMD:
pip show numpy
The output is given below:
How to Configure Python Path
When you first install Python on Windows, it’s important that you configure the path environment variable.
This means you should let your operating system know the path of your installation folder, which will allow the interpreter to refer to this path when running Python files.
We’ve listed a step-by-step guide to setting your environment variable and variables below:
Windows
- Right-click on ‘My Computer’ or ‘This PC,’ and select ‘Properties.’
- Click on ‘Advanced system settings.’
- Go to the ‘Advanced’ tab and click on ‘Environment Variables.’
- In the ‘System variables’ section, locate the ‘Path’ variable, select it, and click on ‘Edit.’
- Add the path to the Python executable (e.g., C:\Python<version>\Scripts;C:\Python<version>), and click ‘OK.’
macOS and Linux
- Open the terminal (Terminal on macOS, and Ctrl + Alt + T on Linux).
- Edit the shell configuration file (~/.bashrc for bash shell, ~/.zshrc for zsh shell).
- Add the following line: export PATH=”/path/to/python-<version>/bin:$PATH”
- Save the file and restart the terminal for the changes to take effect.
How to Verify Python Version and Installation
Before starting any Python project, it’s essential to know the version of Python installed on the system as well as its location.
It’ll help you ensure compatibility between packages, libraries, and other tools.
This section will guide you through verifying your Python version and installation using various Python-related commands and performing cross-platform checks.
1. Python-related Commands
To find the version of Python installed on any platform, you can use the python –version command in the terminal or command prompt.
It returns the Python 2 version installed on your system. To check for the Python 3 version, you can use the python3 –version command instead. These commands help you determine which Python interpreter you are currently using.
In case you are using both Python 2 and Python 3 versions, you can verify the compatibility of a specific module by importing it into the Python interpreter.
For example, to check if the re module is compatible, you can try running the following command:
import re
print(re.__version__)
When you run the above command, you’ll get an output similar to the following:
An output like the above suggests that Python’s re module is compatible with your current Python version.
If you’d like to learn how to switch to the latest version of Python, check out our quick and easy guide on how to update Python.
2. Cross-platform Verification
To find where Python is installed on your system, you can use the following Python code snippet for a cross-platform solution:
import sys
print(sys.executable)
This code will print the location of the Python interpreter executable. Depending on your operating system, this might differ.
The output is given below:
By knowing this location, you can ensure that you are using the correct Python interpreter for your projects.
Troubleshooting Common Python Issues
In this section, we’ll talk about some common issues that you may face when working with Python paths.
Let’s get into it!
1. Path-related Problems
For beginners, one common problem when using Python is related to file paths.
When Python is installed, its location may not be added automatically to the system environment variables PATH.
This could result in the “Python not found” error when trying to run Python scripts or access the Python shell.
To troubleshoot this issue, you can:
- Ensure Python is installed correctly by checking the installation folder, typically found in:
- Windows: C:\Python{version}
- macOS and Linux: /usr/local/bin/python{version}
- Add Python to the PATH variable to make it accessible system-wide:
- Windows: Open the Control Panel, navigate to System and Security > System > Advanced system settings > System Environment Variables, and edit the PATH variable to include the Python installation folder.
- macOS and Linux: Open the terminal and add the Python installation directory to the PATH variable using the export command, such as export PATH=/usr/local/bin/python{version}:$PATH.
- Save and restart the terminal or Command Prompt to apply the changes.
After following the steps above correctly, you’ll no longer run into any errors with running Python files.
2. Version Compatibility
Different Python versions might lead to version compatibility issues, especially when working with third-party modules and libraries.
To overcome this, you can:
- Check your Python version by running python –version in the terminal or Command Prompt.
- Verify the compatibility of a package by checking its documentation or the PyPI page. Packages usually list compatible Python versions.
- Use a virtual environment to manage and isolate dependencies for different projects.
By addressing path-related problems and ensuring version compatibility, you can resolve some of the most common Python issues.
To learn more about error resolution in Python, check the following video out:
Final Thoughts
Understanding where Python is installed on your system is a fundamental aspect of becoming an efficient programmer.
It allows you to manage your programming environment effectively and is key when dealing with using multiple versions of Python versions or when installing modules.
It also helps you in cases when you want to use specific versions for different projects, or when you need to install packages globally or just for one project.
Furthermore, knowing the path of your Python installation can also help you troubleshoot issues related to your environment setup or version conflicts and fine-tune your coding environment to your liking.
It’s an essential step in setting up an integrated development environment, and it makes using code editors or Python-related software smoother and more efficient!
Frequently Asked Questions
In this section, we’ve listed some frequently asked questions that most beginners have related to the Python installation directory.
Where is Python install location on Windows?
Python is installed in the default location C:\PythonXY where XY represents the version number.
For example, C:\Python39 for Python 3.9. It might also get installed under C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXY for per-user installations.
How to find Python location in CMD?
To find the Python installation path in CMD, you can use the following command:
python -c
import os, sys
print(os.path.dirname(sys.executable))
This command imports the os and sys modules and prints the directory of the Python executable.
Where is Python’s location in Windows 10?
On Windows 10, Python’s default location is C:\PythonXY or C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXY for per-user installations.
How to check if Python is installed?
To check if Python is installed, open a command prompt or terminal and type in:
python --version
If Python is installed, the command will display the version of Python.
If it’s not installed, you’ll get an error or the Microsoft Store may open for Python installations in certain cases on Windows.
How to find Python package’s installation location?
Python packages are generally installed in a subfolder of the Python installation. The specific location depends on whether you’re using a virtual environment or not.
To find the installation location of a package, open a terminal or command prompt and type:
pip show package-name
Replace “package-name” with the name of the package you want to find the location for. The output will show the package’s location along with other information.
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