[Python-Dev] sys.path[0]

Thomas Heller theller@python.net
08 Jan 2003 15:36:36 +0100


Guido van Rossum <guido@python.org> writes:

[ping]
> > Exactly for this reason, changing the working directory confuses
> > inspect and pydoc and presumably anything else that tries to find
> > source code.  There's no way to work around this because the true
> > path information is simply not available, unless we fix the
> > __file__ attribute.
> > 
> > I'd be in favour of setting all __file__ attributes to absolute paths.
That's what site.py does:

for m in sys.modules.values():
    if hasattr(m, "__file__") and m.__file__:
        m.__file__ = os.path.abspath(m.__file__)
del m

> 
> Note that code objects have their own filename attribute, which is not
> directly related to __file__, and that's the one that causes the most
> problems.  I truly wish we could change marshal so that when it loads
> a code object, it replaces the filename attribute with the filename
> from which the object is loaded, but that's far from easy. :-(
> 
> > > > I'm disinclined to do anything about this, except perhaps warn that
> > > > the script directory may be given as a relative path.
> > 
> > The current working directory is a piece of hidden global state.
> > In general, hidden global state is bad, and this particular piece
> > of state is especially important because it affects what Python
> > modules get loaded.  I'd prefer for the interpreter to just set
> > up sys.path correctly to begin with -- what's the point in doing
> > it ambiguously only to fix it up later anyway?
> 
> Maybe things have changed, but in the past I've been bitten by
> absolute path conversions.  E.g. I rememeber from my time at CWI that
> automount caused really ugly long absulute paths that everybody
> hated.  Also, there are conditions under which getcwd() can fail (when
> an ancestor directory doesn't have enough permissions) so the code
> doing so must be complex.
> 
> That said, I'd be +0 if someone gave me a patch that fixed the path of
> the script (the only path that's not already absolutized by site.py).

I've submitted a patch #664376 which fixes the problem on Windows,
I cannot do it for other systems.

This patch only converts sys.path[0], it doesn't touch sys.argv[0].

Thomas