我试图找出在运行时可靠地发现py
给定模块的文件在文件系统上的位置的最佳方法。我需要这样做,因为我计划将一些关于某些方法的配置数据外部化(在这种情况下,用于验证来自模块中定义的接口的服务调用的响应的模式)以保持清洁和易于维护。
系统的简化说明:
package
|
|-service.py
|
|-call1.scm
|
|-call2.scm
service.py (_call()
是基类上的一个方法,尽管这与问题无关)
class FooServ(AbstractService):
def call1(*args):
result = self._call('/relative/uri/call1', *args)
# additional call specific processing
return result
def call2(*args):
result = self._call('/relative/uri/call2', *args)
# additional call specific processing
return result
call1.scm 和 call2.scm 定义响应模式(在当前情况下,使用草案 JSON 模式格式,但同样与问题无关)
在代码库的另一个地方,当实际进行服务调用时,我希望能够检测到的位置,service.py
以便我可以遍历文件结构并找到 scm 文件。至少在我的系统上,我认为这会起作用:
# I realize this is contrived here, but in my code, the method is accessed this way
method = FooServ().call1
module_path = sys.modules[method.__self__.__class__.__module__].__file__
schema_path = os.path.join(os.path.dirname(module_path), method.__name__ + '.scm')
但是,我想确保这在所有平台和安装配置上都是安全的,我在进行研究时遇到了这个问题,这让我担心尝试以这种方式执行此操作不会可靠地工作。__file__
这会普遍有效,还是模块对象返回文件位置的事实,该位置pyc
可能位于文件旁边以外的某个位置py
,这会使该解决方案无效?如果它会使其无效,我可以做什么,如果有的话?