Python setuptools:将配置文件分发到操作系统特定的目录

Nef*_*pus 4 python setuptools setup.py

我在使用 Python setuptools 时遇到了先有鸡还是先有蛋的问题。

我想要实现的是将带有我的 pip 包的配置文件(这本身完全可以使用data_files参数 in setup.py)分发到用户配置文件的操作系统特定公共位置(例如~/.config在 Linux 上)。

我发现可以使用appdirs[1] PyPi 包解决操作系统“特异性”问题。还有我的问题 -appdirs在安装我自己的包时不能保证安装,因为它是我的包的依赖项,因此安装在它之后(承诺的鸡或蛋:))

我的setup.py包含这样的东西:

from setuptools import setup
from appdirs import AppDirs
...
setup(
...
    data_files=[
        (AppDirs(name, author).user_config_dir, ['config/myconfig'])
    ],
...
)
Run Code Online (Sandbox Code Playgroud)

这可以在不编写我自己的 setuptools 版本的情况下解决吗(意为典故;))?

[1]:https : //pypi.python.org/pypi/appdirs

she*_*ron 5

正如我在评论中提到的,我建议将文件的通用副本与包一起分发,然后在运行时将其复制到用户的配置目录(如果它不存在)。

这应该不是很难,包括:

  1. 使用setuptools's package_data(而不是data_files)。这会将文件放置在运行时可访问的位置,使用pkg_resources, 在特定操作系统的“正确”位置

  2. 当程序运行时,用于appdirs查找特定于用户的本地安装文件。

  3. 如果不存在,则使用pkg_resources查找文件并将其复制到提供的位置appdirs

虽然我还没有这样做,但这个过程应该可以很好地适用于多个操作系统和环境,并且作为奖励,在开发过程中也是如此,因为它是如何pkg_resources工作的。

例子 setup.py

在 setup.py 中,您应该确保使用以下命令包含您的包的数据文件package_data

setup(
    # ...
    data_files={
        "my_package": [ "my_package.conf.dist" 
    }
    # ...
)
Run Code Online (Sandbox Code Playgroud)

示例应用代码:

import os.path
import pkg_resources
import appdirs

def main():
    """Your app's main function"""
    config = get_config()
    # ... 
    # ...

def get_config():
    """Read configuration file and return its contents
    """
    cfg_dir = appdirs.user_config_dir('MyApplication')
    cfg_file = os.path.join(cfg_dir, 'my_application.conf')
    if not os.path.isfile(cfg_file):
        create_user_config(cfg_file)
    with open(cfg_file) as f:
        data = f.read()
        # ... probably parse the file contents here ...
        return data

def create_user_config(cfg_file):
    """Create the user's config file

    Note: you can replace the copying of file contents using shutil.copyfile
    """
    source = pkg_resources.resource_stream(__name__, 'my_package.conf.dist')
    with open(cfg_file, 'w') as dest:
        dest.writelines(source)
Run Code Online (Sandbox Code Playgroud)

我希望这可以清除pkg_resourcesand的用法package_data