簡體   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