[Python-Dev] Re: [Zope3-dev] Zip import and sys.path manipulation (was Re: directory hierarchy proposal)

Barry A. Warsaw barry@zope.com
Mon, 16 Dec 2002 11:38:13 -0500


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

    >> Random, harried thought: maybe we can use .pth files to extend
    >> the __path__?  IOW, something like the above would search
    >> sys.path for zope.pth files, and do the equivalent to what
    >> site.py already does.

    GvR> That would be a useful addition to the pkgutil.py module that
    GvR> I just proposed.

BTW, in the spirit of TOOWTDI, here's a very quick hack...

-Barry

-------------------- snip snip --------------------
# Use like this:
#
# from pkgutil import extendpath
# __path__ = extendpath(__path__, __name__)

import os
import sys
from site import makepath

def _read(basedir, fp):
    dirs = {}
    # Stolen largely from site.py
    for line in fp:
        if line.startswith('#'):
            continue
        if line.startswith('import'):
            exec line
            continue
        if line.endswith('\n'):
            line = line[:-1]
        dir, dircase = makepath(basedir, line)
        if os.path.exists(dir):
            dirs[dir] = True
    return dirs


def extendpath(path, name):
    path = dict(zip(sys.path, [True for x in sys.path]))
    for dir in sys.path:
        if isinstance(dir, (str, unicode)):
            pth = os.path.join(dir, name + os.extsep + 'pth')
            try:
                fp = open(pth)
            except IOError:
                continue
            try:
                path.update(_read(dir, fp))
            finally:
                fp.close()
    return path.keys()