[Tutor] sys.path and the path order

Dave Angel davea at ieee.org
Fri Apr 23 10:23:30 CEST 2010


Garry Willgoose wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">My 
> question is so simple I'm surprised I can't find an answer somewhere. 
> I'm interested if I can rely on the order of the directories in the 
> sys.path list. When I'm running a file from the comand line like
>
> python tellusim.py
>
> The string in entry sys.path[0] appears to be the full path to the 
> location of the file I'm running in this case tellusim ... i.e. it 
> looks like '/Volumes/scone2/codes/tellusim0006'. This is good because 
> for my code I need to create a search path for modules that is 
> relative to the location of this file irrespective of the location I'm 
> in when I invoke the script file (i.e. I could be in /Volumes/scone2 
> and invoke it by 'python codes/tellusim0006/tellusim.py').
>
> The question is can I rely on entry [0] in sys.path always being the 
> directory in which the original file resides (& across linux, OSX and 
> Windows)? If not what is the reliable way of getting that information?
>
As Steven says, that's how it's documented.

There is another way, one that I like better.  Each module, including 
the startup script, has an attribute called __file__, which is the path 
to the source file of that module.

Then I'd use os.path.abspath(), and os.path.dirname() to turn that into 
an absolute path to the directory.

The only exception I know of to __file__ usefulness is modules that are 
loaded from zip files.  I don't know if the initial script can come from 
a zip file, but if it does, the question changes.

DaveA



More information about the Tutor mailing list