[Tutor] where am I, revisited

Sheila King sheila@thinkspot.net
Fri, 01 Mar 2002 23:05:23 -0800


On Fri, 01 Mar 2002 11:01:49 -0800, "Jeff Shannon" <jeff@ccvcorp.com>
wrote about Re: [Tutor] where am I, revisited:

> > fullpathtoscript = os.path.split(os.path.abspath(sys.argv[0]))
> > .....
> > path=fullpathtoscript[0]
> 
> This is not necessarily reliable.  os.path.abspath() does *not* specifically find a file.  It
> does a simple text substitution to convert a relative path to an absolute path, based on the
> current working directory, which is *not* necessarily where your script lives.  (In a cgi
> environment, it may be a valid assumption, but I wouldn't rely on it.)
> 
> I think that a better option would be to use the __file__ attribute of on of your modules.
> This contains the (fully qualified) path of the file that the module was loaded from.
> 
> >>> import os
> >>> print os.__file__
> C:\PYTHON21\lib\os.pyc
> >>>
> 
> You can thus use os.path.dirname(mymodule.__file__) to get the directory that the module is
> in.

It has taken me a while to wrap my brain around what you are saying here,
but I think I understand it now.

However, I don't think your suggested fix will work for the particular
script *I'm* running (where I got this suggestion that I made to Kirk). The
modules from the standard Python library are in a completely different
location, and I have no modules that I'm using in the same location as the
script. I get the impression that
sys.argv[0].__file__

probably doesn't work? I have to do that on an imported module? But I have
no imported module in that directory, so...

For the particular script I'm running, which is a mail filter script that
runs when it is called by Qmail, it will give me the correct working
directory. But I appreciate your caution that I cannot assume it in all
cases.

-- 
Sheila King
http://www.thinkspot.net/sheila/

"When introducing your puppy to an adult cat,
restrain the puppy, not the cat." -- Gwen Bailey,
_The Perfect Puppy: How to Raise a Well-behaved Dog_