How should I create and read a user editable configuration file in ~/.config or similar?

一世执手 提交于 2021-02-05 06:36:08

问题


I am planning a command line Python application that I intend to distribute through PyPi.

When the application is installed with pip, I want to create a user-editable configuration file in the appropriate location on the user's filesystem.

For example, in Ubuntu, the file would be something like ~/.config/foo/config.ini

On installation I want to create the file (if possible) and be able to specify another config file to use instead with a command line parameter.

What is the usual scheme for getting this done?


回答1:


I think appdirs package on PyPI is what you need, isn’t it?




回答2:


A project such as xdgappdirs (which is derived from appdirs) can help with such a task. It implements Freedesktop's "XDG Base Directory Specification".

Don't create the file at installation time though. It is preferable to create the file when it is actually needed, this might be during the first run of the application for example.

Something like the following should get you started with the configuration directory:

>>> import appdirs
>>> appdirs.user_config_dir('foo')
'/home/sinoroc/.config/foo'

Or without external dependency, it could roughly look like this:

#!/usr/bin/env python3

import argparse
import os
import pathlib
import platform

def get_config_file_path(project_name, file_name):
    path = None
    config_path = None
    platform_system = platform.system()
    if platform_system == 'Windows':
        if 'APPDATA' in os.environ:
            config_path = pathlib.Path(os.environ['APPDATA'])
        else:
            config_path = pathlib.Path.home().joinpath('AppData', 'Roaming')
    elif platform_system == 'Linux':
        if 'XDG_CONFIG_HOME' in os.environ:
            config_path = pathlib.Path(os.environ['XDG_CONFIG_HOME'])
        else:
            config_path = pathlib.Path.home().joinpath('.config')
    if config_path:
        path = config_path.joinpath(project_name, file_name)
    return path

def main():
    default_config_file_path = get_config_file_path('foo', 'config.ini')
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument(
        '--config', '-c',
        default=str(default_config_file_path),
        type=argparse.FileType('r'),
    )
    args = args_parser.parse_args()

if __name__ == '__main__':
    main()



回答3:


You should use the appdirs module for this as it reliably handles differences across different platforms:

>>> from appdirs import user_config_dir
>>> appname = "SuperApp"
>>> appauthor = "Acme"
>>> user_config_dir(appname)
'/home/trentm/.config/SuperApp'


来源:https://stackoverflow.com/questions/59348090/how-should-i-create-and-read-a-user-editable-configuration-file-in-config-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!