gpt4 book ai didi

Python 安装工具 : Distribute configuration files to OS specific directories

转载 作者:行者123 更新时间:2023-11-28 17:23:46 31 4
gpt4 key购买 nike

我在使用 Python 设置工具时遇到了先有鸡还是先有蛋的问题。

我想要实现的是用我的 pip 包分发一个配置文件(这本身完全可以通过 setup.py 中的 data_files 参数实现)到用户配置文件的特定操作系统通用位置(例如 Linux 上的 ~/.config)。

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

我的 setup.py 包含如下内容:

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

是否可以在不编写我自己的 setuptools 版本的情况下解决这个问题(暗示 ;))?

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

最佳答案

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

这应该不是很难,涉及:

  1. 使用setuptoolspackage_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"
}
# ...
)

示例应用代码:

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)

我希望这可以清除 pkg_resourcespackage_data 的用法。

关于Python 安装工具 : Distribute configuration files to OS specific directories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40193112/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com