简体   繁体   中英

Best practice to use Python configparser module and get values?

I code a simple Python project and I want to use configparser module to get values from config.ini file.

I did it in this way:

#!/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']

But, now the problem is I have to new an ConfigReader object everytime, then I can use the get_mac_chrome_driver() function(to get value of config['mac']['chrome_driver_path']).

I believe it is not the best practice and is not pythonic.

May I just use it by from utls.ConfigReader import CHROME_DRIVER_PATH ?

Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM