Python module along the way

I am writing a minimal replacement for mod_python publisher.py

The basic premise is that it loads modules based on the URL scheme:

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

      

In this case / foo / could be a directory, and "bar" is the ExposedBar method in the published class at /foo/index.py. Likewise, / foo can appear in /foo.py, and bar is a method in a public class. The semantics of this are not very 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

      

The module is then checked against the corresponding classes / functions / methods. When the process reaches as far as possible the remaining URI data, / a / b / c is passed to that method or function.

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

When viewed in a browser, it is pretty random, which is selected by "index.py" although I set the first search path to "/ var / www / html / foo" or "/ var / www / html / bar 'and then loaded with __import __ ('index'). I have no idea why it finds either random selection. This shows:

__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"

      

The question then is why __import__ will randomly choose any index. I would understand this if the path was "/ var / www / html", but it is not. Secondly:

Can I load a module with an absolute path to the module object? Without changing sys.path. I cannot find any docs for __import__ or new.module () for this.

+1


a source to share


1 answer


Can I load a module by absolute path to the module object? No modification to sys.path. I cannot find any docs in __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))

      

+3


a source







All Articles