Add to python path mac os x

Viewed 319595

I thought

import sys
sys.path.append("/home/me/mydir")

is appending a dir to my pythonpath

if I print sys.path my dir is in there.

Then I open a new command and it is not there anymore.

But somehow Python cant import modules I saved in that dir.

What Am I doing wrong?

I read .profile or .bash_profile will do the trick.

Do I have to add:

PATH="/Me//Documents/mydir:$PYTHONPATH"
export PATH

To make it work?

7 Answers

On MAC OS you can simply find the location of python/python3 by using the command which python or which python3. (works for Linux too)

And it should give something like:

For python

/usr/local/bin/python

For python3

/Library/Frameworks/Python.framework/Versions/3.9/bin/python3

Export the path to your bash_profile

In your terminal type

sudo nano ~/.bash_profile

Enter your password and paste the following lines

PYTHONPATH="/Library/Frameworks/Python.framework/Versions/3.9/bin/python3"
export PYTHONPATH

Press control + x to exit, and press y for saving on being asked to save

Press `enter' to return to terminal window

Source it using the following command in terminal, run

source ~/.bash_profile

Path to python3 should be updated now!!

On MacOS Big Surf the file to add the "export" is $HOME/.zprofile

So, this should work for adding PYTHONPATH to your Mac Big Surf environment variables:

export PYTHONPATH=$HOME/my_folder

If the file doesn't exist just create it in $HOME, normally /Users/my_user_name

This change in the file name is because the default shell for MacOS Big Surf is zsh and not bash

In my .zshrc file located at /Users/your_username/.zshrc

I add the following line: export PYTHONPATH="${PYTHONPATH}:/your/path" and save it.

If the file doesn't exist, create a nameless .txt file and change its extension to .zshrc. It's a hidden file, so you need to press cmd+shift+. to see it.

I am using macOS Monterey.

Related