Monday 13 January 2014

The Python path

After the rather long introduction to the Bash path we can now move on to the Python path.

Like the Bash path the Python path can be set in different ways. The path can be added to from your .bash_profile using a line such as

export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/GDAL.framework/Versions/1.10/Python/2.7/site-packages

This line works in pretty much the same way as the other PATH exports do in your .bash_profile except that Python reads this variable. So you could just add to your Python path using this method; however, a more common way for Python paths to be added is to use *.pth files stored in locations already on the path.

Basically, Python starts by looking in its own set of directories for all the standard tools it comes with, such as "sys", then if it encounters a file with the extension "pth" it tries to read that file and add the path contained therein to the Python path.

Before we go on with the *.pth files lets look at the address shown in the path export above; it ends with "site-packages" which is a useful folder found in many Python libraries and there is even one in the Python installation directory. As noted in the previous post, I use Anaconda which is a bundle that includes the basic Python installation plus many other useful packages/libraries. So, looking at my Python installation we get the following:

The site-packages directory of my Python installation
As you can see from the image above, my Python installation contains a directory called "site-packages". This directory can contain libraries and files that you install or write yourself, the name "site-packages" implying "things local to this site/computer". It may also contain *.pth files, four of which can be seen listed in the image above.
The paths contained in these files are appended to the sys.pth file by Python automatically. According to Python's own documentation you may alter the sys.pth file as well but this file will be overwritten during an update of Python so it is best to not do that.
The AM_functions.pth file contains the following line:

import sys; sys.path.insert(0,'/Users/andrew/Dropbox/5_Python/Functions')

which is perhaps overkill when a simple

/Users/andrew/Dropbox/5_Python/Functions

would suffice. Which ever type you use the address will be added to the path and the files therein will be found by Python. The advantage of the sys.path.insert method is that I can specify where in the path order the address should be inserted. The number "0" after the opening parenthesis tells Python to insert the address at the first location of the path list (Python counts from 0, not from 1).

That should cover most of the basics of paths, there are some specific path issues that I will deal with as appropriate, especially concerning Anaconda and GDAL, but all that fun will have to wait.


No comments:

Post a Comment