views:

257

answers:

1

I am writing a minimal replacement for mod_python's publisher.py

The basic premise is that it is loading modules based on a URL scheme:

/foo/bar/a/b/c/d

Whereby /foo/ might be a directory and 'bar' is a method ExposedBar in a publishable class in /foo/index.py. Likewise /foo might map to /foo.py and bar is a method in the exposed class. The semantics of this aren't really important. I have a line:

sys.path.insert(0, path_to_file)  # /var/www/html/{bar|foo}
mod_obj = __import__(module_name)
mod_obj.__name__ = req.filename

Then the module is inspected for the appropriate class/functions/methods. When the process gets as far as it can the remaining URI data, /a/b/c is passed to that method or function.

This was working fine until I had /var/www/html/foo/index.py and /var/www/html/bar/index.py

When viewing in the browser, it is fairly random which 'index.py' gets selected, even though I set the first search path to '/var/www/html/foo' or '/var/www/html/bar' and then loaded __import__('index'). I have no idea why it is finding either by seemingly random choice. This is shown by:

__name__ is "/var/www/html/foo/index.py"
req.filename is "/var/www/html/foo/index.py"
__file__ is "/var/www/html/bar/index.py"

This question then is, why would the __import__ be randomly selecting either index. I would understand this if the path was '/var/www/html' but it isn't. Secondly:

Can I load a module by it's absolute path into a module object? Without modification of sys.path. I can't find any docs on __import__ or new.module() for this.

+2  A: 

Can I load a module by it's absolute path into a module object? Without modification of sys.path. I can't find any docs on __import__ or new.module() for this.

import imp
import os

def module_from_path(path):
    filename = os.path.basename(path)
    modulename = os.path.splitext(filename)[0]

    with open(path) as f:
        return imp.load_module(modulename, f, path, ('py', 'U', imp.PY_SOURCE))
dF
Wonderful. Thanks very much. Being new to Python I expected import to have an easy 'by path' mechanism like dlopen() in C
Aiden Bell
works like a charm :) thanks dF
Aiden Bell