[Python-Dev] package imports, sys.path and os.chdir()

Nick Coghlan ncoghlan at gmail.com
Sun Apr 29 07:05:17 CEST 2012

On Sun, Apr 29, 2012 at 1:41 PM, PJ Eby <pje at telecommunity.com> wrote:
> That's already the case.  Actually, sys.path[0] is *always* the absolute
> path of the script directory -- regardless of whether you invoked the script
> by a relative path or an absolute one, and regardless of whether you're
> importing 'site' -- at least on Linux and Cygwin and WIndows, for all Python
> versions I've used regularly, and 3.2 besides.

"-c" and "-m" also insert the empty string as sys.path[0] in order to
find local files. They could just as easily insert the full cwd
explicitly though, and, in fact, they arguably should. (I say
arguably, because changing this *would* be a backwards incompatible
change - there's no such issue with requiring __file__ to be

If we fixed that, then you could only get relative filenames from the
interactive prompt.

There's another way we can go with this, though: something I'm working
on at the moment is having usage of the frozen importlib be
*temporary*, switching to the full Python source version as soon as
possible (i.e. as soon as the frozen version is able to retrieve the
full version from disk).

There's a trick that becomes possible if we go down that path: we can
have some elements of importlib._bootstrap that *don't run* during the
initial bootstrapping phase.

Specifically, we can have module level code that looks like this:

    if __name__.startswith("importlib."):
        # Import system has been bootstrapped with the frozen version,
we now have full stdlib access
        # and other parts of the interpreter have also been fully initialised
        from os.path import abspath as _abspath
        _debug_msg = print
        # Running from the frozen copy, there's things we can't do yet
because the interpreter is not fully configured
        def _abspath(entry):
            # During the bootstrap process, we let relative paths
slide. It will only happen if someone shadows the stdlib in their
            # current directory.
            return entry
        def _debug_msg(*args, **kwds):
            # Standard streams are not initialised yet


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list