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

问题描述 投票:2回答:1

我编写一个简单的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'] ['chrome_driver_path']的值)。

我相信这不是最好的做法,也不是pythonic。

我可以用from utls.ConfigReader import CHROME_DRIVER_PATH来使用它吗?

谢谢!

python configparser
1个回答
0
投票

在阅读Django源代码之后,在settings.py中编写参数/值可能更“pythonic”,请参阅https://github.com/django/django/blob/master/django/conf/global_settings.py

© www.soinside.com 2019 - 2024. All rights reserved.