从python包代码确定安装方案/前缀

说,我有一些
python包,setup.py有以下几行:

...
packages=['mypkg'],
data_files=[
    ('lib/mypkg/', [...]),
    ('share/mypkg/', [...]),
]
...

我假设将在$(前缀)/ lib / mypkg上安装几个可执行帮助程序,并且将在$(前缀)/ share / mypkg上安装与程序包相关的数据文件.关键是$(前缀)可能因不同的发行版而异.例如,默认情况下我在centos系统上有前缀= / usr,默认情况下在debian系统上有前缀= /usr/local.此外,据我所知,自定义前缀甚至自定义安装方案可以作为setup.py参数提供.

所以,我希望能够使用我的包中的python代码严格确定我的包数据的安装位置.目前我正在使用以下解决方案,但它对我来说似乎很笨拙,我认为在自定义安装方案的情况下效率会很低:

# mypkg/__init__.py
import os
initpath = __path__[0]

while True:
    datapath, _ = os.path.split(initpath)
    if datapath == initpath:
        break
    initpath, datapath = datapath, os.path.join(datapath, 'share', 'mypkg')
    if os.path.exists(datapath):
        print datapath

有没有更好的方法呢?

最佳答案 我编写的方法是以下代码:

import sysconfig
import pkg_resources

self.install_scheme = None
distribution = pkg_resources.get_distribution( 'mypkg' )
lib_path = distribution.location
schemes = sysconfig.get_scheme_names()
for s in schemes:
    p = sysconfig.get_path( 'purelib', s )
    if p == lib_path:
        self.install_scheme = s

这适用于通过pip安装的包,其中创建了包元数据.将self.install_scheme更改为您可以访问所需位置的变量(在我的情况下,对象上的实例变量都可以访问),并像这样使用它:

data_path = sysconfig.get_path( 'data', self.install_scheme )

如果self.install_scheme为None,我只是使用sysconfig.get_path()而没有方案名称(给我我的平台的默认方案)并希望最好.

点赞