How to get the author’s name, project description, etc. From the Distribution object to pkg_resources?

pkg_resources api allows you to get distribution objects that represent the distribution of eggs within a directory. I can trivially get the project name and distribution version with dist.project_nameand dist.version, however, I have lost the way I can get other metadata that is usually specified in the script setting (for example, author, description, etc.) ..)

+3
source share
2 answers

I watched how to do the same. This is what I came up with. This is probably not the best solution, but seems to work.

# get the raw PKG-INFO data
from pkg_resources import get_distribution
pkgInfo = get_distribution('myapp').get_metadata('PKG-INFO')

# parse it using email.Parser
from email import message_from_string
msg = message_from_string(pkgInfo)
print(msg.items())

# optional: convert it to a MultiDict
from webob.multidict import MultiDict
metadata = MultiDict(msg)
print(metadata.get('Author'))
print(metadata.getall('Classifier'))
+2
source

. , package.py mymodule , setup.py. setup.py:

pkg_info = get_package_info('mymodule')
setup(**pkg_info)

setup.py import mymodule.package as pkg_info, , setup.py . setup.py get_package_info(module_name):

def get_package_info(module_name):
    '''
    Read info about package version, author etc
    from <module_name>/package.py

    Return:
        dict {'version': '1.2.3', 'author': 'John Doe', ...}
    '''
    here = os.path.dirname(os.path.abspath(__file__))
    code_globals = {}
    code_locals = {}
    with open(os.path.join(here, module_name, 'package.py')) as f:
        code = compile(f.read(), "package.py", 'exec')
        exec(code, code_globals, code_locals)
    return code_locals

mymodule/package.py:

# -*- coding: utf-8 -*-
name = 'mymodule'
version = '1.2.3'
description = 'My module for demonstration'
url = 'https://github.com/myorg/mymodule'
author = 'John Doe'
author_email = 'john.doe@example.com'

...

packages = ['mymodule']
install_requires = ['myotherpackage', 'somepackage']

...

, , : from mymodule.package import version, author. , .

0

All Articles