How to add Python to PATH on macOS, Linux, Windows

Feb 18, 2024#python#cli

The PATH is an environment variable on operating systems like Windows, macOS, and Linux. It contains a list of directories that the operating system uses to search for executable files (programs) when a command is entered in the command prompt or terminal.

When you type a command in the command prompt or terminal, the system searches through the directories listed in the PATH variable to find the corresponding executable file for that command. If the executable is found in one of the directories, the command is executed. If not, the system will report that the command is not recognized.

Adding Python to the PATH allows you to run Python commands or scripts from any location in the command prompt or terminal without specifying the full path to the Python executable.

Here are the general steps on different operating systems:

Linux and macOS

The process of adding Python to the PATH is similar on both Linux and macOS, as they share a common command-line environment and file structure. Here are the general steps for each:

  1. Open a terminal window.
  2. Open your shell configuration file using a text editor. For Bash, it’s usually ~/.bashrc or ~/.bash_profile. For Zsh, it’s ~/.zshrc.
  3. Add the following line at the end of the file, replacing /path/to/python with the actual path to your Python installation directory:
export PATH="/path/to/python/bin:$PATH"
  1. Save and close the file.
  2. Run source ~/.bashrc or source ~/.zshrc (or restart your terminal) to apply the changes.

Windows

The difference in adding Python to the PATH on Windows compared to Linux and macOS primarily stems from the distinct design and conventions of the operating systems. Each operating system has its own way of handling environment variables and configuring system paths.

Windows uses a graphical user interface for environment variable settings. Users can access these settings through the System Properties window and easily modify the PATH variable by adding new directories.

  1. First, locate the directory where your Python executable (usually python.exe) resides. It could be in C:\Python\ or your AppData\Local\Programs\Python folder.
  2. Verify that the executable works by double-clicking it and ensuring it opens a Python REPL.
  3. To add it to the PATH:
  • Open System Properties (you can type it in the start menu or use the keyboard shortcut Win + Pause).
  • Switch to the Advanced tab.
  • Click Environment Variables.
  • Under System variables, find PATH and click Edit.
  • Add the path to your Python executable (e.g., C:\Python\) at the end of the list (separated by semicolons).
  • Restart the Command Prompt.
  1. You’re all set! Now you can run Python from anywhere in the command line.