Python 模块(按路径)
我正在编写 mod_python 的publisher.py 的最小替代品,
基本前提是它基于 URL 方案加载模块:
/foo/bar/a/b/c/d
其中 /foo/ 可能是一个目录,而 'bar' 是 /foo/ 中可发布类中的 ExusedBar 方法索引.py。 同样,/foo 可能映射到 /foo.py,而 bar 是公开类中的一个方法。 这个的语义并不重要。 我有一句话:
sys.path.insert(0, path_to_file) # /var/www/html/{bar|foo}
mod_obj = __import__(module_name)
mod_obj.__name__ = req.filename
然后检查模块是否有适当的类/函数/方法。 当进程尽可能获取剩余的 URI 数据时,/a/b/c 将传递给该方法或函数。
这工作正常,直到我有 /var/www/html/foo/index.py 和 /var/www/html/bar/index.py
在浏览器中查看时,选择哪个“index.py”是相当随机的,即使我将第一个搜索路径设置为“/var/www/html/foo”或“/var/www/html/bar”,然后加载 __import__('index')。 我不知道为什么它是通过看似随机的选择来找到的。 这表明:
__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"
这个问题是,为什么 __import__ 会随机选择任一索引。 如果路径是“/var/www/html”我会理解这一点,但事实并非如此。 其次:
我可以通过模块的绝对路径将模块加载到模块对象中吗? 无需修改 sys.path。 我找不到关于 __import__ 或 new.module() 的任何文档。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)