Wednesday, May 9, 2012

How to add python path to import external module (tested on python 2.7 mac osx)


option #1 : using site-packages folder
The location of python 2.7 framework is in /Library , this is different with python 2.6 which is installed in /System/Library. So inside the python framework folder , find the site-packages folder :
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
you can (choose one) :

  • put any external modules here, python will look up external modules from here automatically OR
  • keep the external modules in any folder you want , then in the 'site-packages' folder above, put/create any text file and name it <name>.pth , you can use any generic name like : mypath.pth etc. Then inside this file , type your path where the modules are located

Now open python shell and type module you want to import. ex: import myModule

option #2 : sys module
in the python file, add these code :

import sys
sys.path.append(path_to_modules) #ex: sys.path.append('/data/lib')
import <myModules_name> #test calling/import module

you can insert path into the beginning of the path list, by insert to index(0) :
sys.path.insert(0, path_to_module)

option #3 : .bash_profile
add these code into .bash_profile

# add python path

PYTHONPATH='path_to_modules_folder : $PYTHONPATH'

export PYTHONPATH

or
export PYTHONPATH = "/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/AppKit.framework/Versions/C/Headers/"

No comments:

Post a Comment