1

我需要从两个配置文件中的三个不同可能位置读取某个路径:

  • 一个全球性的,/etc/program.conf
  • 一个本地人,~/.config/program/config

本地的有一个[DEFAULT]部分,可能有也可能没有每个案例特定的部分,比如说[case]。我想

  1. 读取本地配置的特定案例部分给出的路径
  2. 如果没有,请阅读本地配置的默认部分给出的路径
  3. 如果没有,请阅读全局配置给出的路径
  4. 如果没有 (!),请提供默认路径

configparser在 Python 中使用。这实际上不是一个难题,但我想出的解决方案让我觉得不优雅和笨拙。我认为这是一种相当普遍的情况,我想我会向更有经验的程序员寻求更好的解决方案。

我的代码是这样的:

def retrieve_download_path(feed):
    download_path = os.path.expanduser('~/Downloads')
    config = configparser.ConfigParser()
    if os.path.isfile(CONFIG_FILENAME_GLOBAL):
        config.read(CONFIG_FILENAME_GLOBAL)
        if config.has_option('DEFAULT','Download directory'):
            download_path = os.path.expanduser(config['DEFAULT']['Download directory'])
    if os.path.isfile(CONFIG_FILENAME_USER):
        config.read(CONFIG_FILENAME_USER)
        if config.has_option(feed,'Download directory'):
            download_path = os.path.expanduser(config[feed]['Download directory'])
        elif config.has_option('DEFAULT','Download directory'):
            download_path = os.path.expanduser(config['DEFAULT']['Download directory'])
    return download_path

我该如何改进呢?采购不同配置文件的常用方法是什么?

4

1 回答 1

1

configparser似乎为您尝试实现的内容提供支持,特别是多个配置文件和一个DEFAULT部分。

这是做你想做的吗?

def retrieve_download_path(feed):
    # Read the config files.
    config = configparser.ConfigParser()
    config.read((CONFIG_FILENAME_GLOBAL, CONFIG_FILENAME_USER))

    # Resolve the section (configparser doesn't fallback to DEFAULT if the entire section is missing).
    section = feed if config.has_section(feed) else config.default_section

    # Extract the download path.
    download_path = config.get(section, 'Download directory', fallback='~/Downloads')

    # Expand the user directory.
    return os.path.expanduser(download_path)

我看到的唯一区别是它将允许(并咨询)DEFAULT全局配置文件中的一个部分(这似乎是可取的)。

于 2012-11-13T20:08:46.950 回答