my parser.py isn't imported

Torsten Bronger bronger at physik.rwth-aachen.de
Mon Aug 27 05:36:14 EDT 2007


Hallöchen!

John Machin writes:

> Torsten Bronger wrote:
>
>> I have a module parser.py in the same directory as the main
>> module.  In the main module, I import "parser".  On Linux, this
>> works as expected, however on Windows, it imports the stdlib
>> parser module.  sys.path[0] points to the directory of my
>> parser.py in both cases.  What went wrong here?
>
> [...]
>
> 2. Failure to RTFabulousM:
> """
> Details of the module searching and loading process are implementation
> and platform specific. It generally involves searching for a ``built-
> in'' module with the given name and then searching a list of locations
> given as sys.path.
> """

Okay, I did the following to avoid this:

import sys, os.path
modulepath = os.path.abspath(os.path.dirname(sys.argv[0]))
def import_local_module(name):
    """Load a module from the local modules directory.

    Loading e.g. a local "parser" module is difficult because on
    Windows, the stdlib parser module is a built-in and thus loaded
    with higher priority.  With
    http://www.python.org/dev/peps/pep-0328/ it may become simpler.

    :Parameters:
      - `name`: name of the module, as it would be given to
        ``import``.

    :Return:
      the module object or ``None`` if none was found

    :rtype:
      module
    """
    import imp
    try:
        return sys.modules[name]
    except KeyError:
        pass
    fp, pathname, description = imp.find_module(name, [modulepath])
    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
                                      Jabber ID: bronger at jabber.org
                      (See http://ime.webhop.org for ICQ, MSN, etc.)



More information about the Python-list mailing list