繁体   English   中英

使用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'] ['chrome_driver_path']的值)。

我认为这不是最佳做法,也不是pythonic。

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

谢谢!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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