使用 Python configparser 模块并获取值的最佳实践?

Best practice to use Python configparser module and get values?

我编写了一个简单的 Python 项目,我想使用 configparser 模块从 config.ini 文件中获取值。

我是这样做的:

#!/usr/bin/env python3

import configparser
import os
import sys

class ConfigReader(object):

    def __init__(self, base_path):
        self.__config_path = os.path.join(base_path, 'config', 'config.ini')
        if os.path.exists(self.__config_path):
            self.config = configparser.ConfigParser()
            self.config.read(self.__config_path)
        else:
            raise FileNotFoundError(
                'Config file is NOT present as "' + self.__config_path + '" !')

    def get_mac_chrome_driver(self):
        return self.config['mac']['chrome_driver_path']

    def get_win_chrome_driver(self):
        return self.config['win']['chrome_driver_path']

但是,现在的问题是我每次都必须新建一个 ConfigReader 对象,然后我可以使用 get_mac_chrome_driver() 函数(获取 config['mac'][[=26 的值=]]).

我认为这不是最佳实践,也不是 pythonic。

我可以在 from utls.ConfigReader import CHROME_DRIVER_PATH 之前使用它吗?

谢谢!

看完Django源码后,直接把parameters/values写成settings.py可能更'pythonic',见https://github.com/django/django/blob/master/django/conf/global_settings.py