Define installation scheme / prefix from python package code

Let's say I have a python package with setup.py with the following lines:

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

I assume that several executable helpers should be installed in $(prefix)/lib/mypkg, and the data files associated with the package should be installed in $(prefix)/share/mypkg. The fact is that it $(prefix)can vary between different distributions. For example, the default is centos and prefix=/usr/localI have prefix=/usrthe default debian. Moreover, since I know that a custom prefix or even a custom installation scheme can be represented as a setup.py parameter.

So, I want to be able to strictly determine where my package data was installed using the python code from my package. Right now I'm using the following solution, but it seems awkward for me, and I believe that it will be ineffective in the case of a custom installation scheme:

# 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

Is there a better way to do this?

+4
source share
1 answer

I developed the following code:

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

This works for a package installed through pipwhere the package metadata was created. Change self.install_schemeas a variable that you have access to where you need it (in my case, an instance variable of an object that everyone can access) and use it as follows:

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

self.install_scheme None, sysconfig.get_path() ( ) .

+2

Source: https://habr.com/ru/post/1568621/


All Articles