获取modu py文件路径的可靠方法

2024-04-16 06:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出在运行时可靠地发现给定模块的py文件在文件系统中的位置的最佳方法。我之所以需要这样做,是因为我计划将一些关于某些方法的配置数据外部化(在本例中,用于验证来自服务调用的响应的模式,这些服务调用的接口是在模块中定义的),以便保持干净和易于维护。在

系统的一个简化的幻象:

package
|
|-service.py
|
|-call1.scm
|
|-call2.scm

在服务.py(_call()是基类上的一个方法,尽管这与问题无关)

^{pr2}$

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')

但是,我想确保这在所有平台和安装配置上都是安全的,我在做研究时遇到了this,这让我担心这样做不会可靠。这种方法是否普遍有效,或者模块对象上的__file__返回pyc文件的位置,该文件可能位于py文件旁边的某个位置,这会使该解决方案无效吗?如果它会使它失效,那我能做什么呢?在


Tags: 模块文件path方法py定义系统service
1条回答
网友
1楼 · 发布于 2024-04-16 06:33:08

PEPyou链接中,它说:

In Python 3, when you import a module, its __file__ attribute points to its source py file (in Python 2, it points to the pyc file).

所以在python3中,您很好,因为__file__总是指向.py文件。在Python2中,它可能指向.pyc文件,但该.pyc只与python2的.py文件位于同一目录中。在


好吧,我想你指的是这一点:

Because these distributions cannot share pyc files, elaborate mechanisms have been developed to put the resulting pyc files in non-shared locations while the source code is still shared. Examples include the symlink-based Debian regimes python-support [8] and python-central [9]. These approaches make for much more complicated, fragile, inscrutable, and fragmented policies for delivering Python applications to a wide range of users.

我相信这些机制只适用于发行版打包的Python模块。我不认为它们会影响到在发行版的打包系统之外手动安装的模块。为该发行版打包模块的人有责任确保该模块不会被该机制破坏。在

相关问题 更多 >