7

pkg_resources api 让您获取表示目录内鸡蛋分布的分布对象。dist.project_name我可以使用和轻松获取项目名称和分发版本dist.version,但是我不知道如何获取通常在安装脚本中指定的其他元数据(如作者、描述等)

4

2 回答 2

4

我正在寻找如何做同样的事情。这就是我想出的。这可能不是最好的解决方案,但似乎有效。

# 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'))
于 2014-02-02T23:17:27.013 回答
-1

这里同样的问题。我通过创建一个包含所有变量的文件来解决它,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 需要它定义的模块。get_package_info(module_name)因此需要自定义导入方法setup.py

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. 此外,信息只需要存储在一个地方。

于 2016-03-09T14:09:23.623 回答