To add a directory to Python’s PATH
on macOS, you can follow these steps depending on whether you want to make the change temporary or permanent:
1. Temporary Addition
A temporary change only lasts for the current session.
Method 1: Modify PYTHONPATH
in the Terminal
Run the following command in your terminal before starting Python:
export PYTHONPATH=$PYTHONPATH:/path/to/your/directory
This adds /path/to/your/directory
to the PYTHONPATH
for the current terminal session.
Verify by starting Python and printing sys.path
:
python
>>> import sys
>>> print(sys.path)
2. Permanent Addition
A permanent change ensures the directory is always part of the Python PATH
.
Method 1: Edit Shell Configuration File
- Determine Your Shell: Check which shell you are using:
echo $SHELL
- If you see
zsh
, edit.zshrc
. - If you see
bash
, edit.bash_profile
.
- If you see
- Open the Configuration File: Open your shell configuration file in a text editor. For example:
nano ~/.zshrc
or
nano ~/.bash_profile
- Add to
PYTHONPATH
: Add the following line at the end of the file:export PYTHONPATH=$PYTHONPATH:/path/to/your/directory
- Apply the Changes: Save the file and reload the configuration:
source ~/.zshrc
or
source ~/.bash_profile
- Verify: Start Python and check if the path is added:
python >>> import sys >>> print(sys.path)
Method 2: Use .pth
Files
If you want Python to always include the directory in sys.path
, regardless of how Python is started, use a .pth
file.
- Find the
site-packages
Directory: Run the following command to locate thesite-packages
directory:python -m site
Look for the path like:
/Library/Frameworks/Python.framework/Versions/3.x/lib/python3.x/site-packages
- Create a
.pth
File: Create a.pth
file in thesite-packages
directory. For example:echo "/path/to/your/directory" > /Library/Frameworks/Python.framework/Versions/3.x/lib/python3.x/site-packages/my_path.pth
- Verify: Start Python and check if the path is added:
python >>> import sys >>> print(sys.path)
3. Using sys.path.append
in a Script
If the directory needs to be added only for a specific script:
import sys
sys.path.append('/path/to/your/directory')
This approach is useful for script-specific modifications.
Conclusion
- Use
sys.path.append
orexport PYTHONPATH
for temporary solutions. - Edit shell configuration files or use
.pth
files for permanent changes.
Let me know if you encounter any issues!