[英]Python: Not able to read properties from property file
我正在嘗試從屬性文件中讀取配置並將這些屬性存儲在變量中,以便可以從任何其他類訪問它。
我能夠從配置文件中讀取配置並打印相同但是當從其他類訪問這些變量時我得到一個異常。
我的配置文件
Config.cfg.txt
[Ysl_Leader]
YSL_LEADER=192
通用類,我將我的屬性存儲在變量中。 ConfigReader.py
import configparser
class DockerDetails:
config = configparser.RawConfigParser()
_SECTION = 'Ysl_Leader'
config.read('Config.cfg.txt')
YSL_Leader = config.get('Ysl_Leader', 'YSL_LEADER')
print(YSL_Leader)
我試圖得到'YSL_Leader'值的另一個類
def logger(request):
print(ConfigReader.DockerDetails.YSL_Leader)
例外:
File "C:\Users\pvivek\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 780, in get
d = self._unify_values(section, vars)
File "C:\Users\pvivek\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 1146, in _unify_values
raise NoSectionError(section) from None
configparser.NoSectionError: No section: 'Ysl_Leader'
僅供參考:當我單獨運行ConfigReader.py時,我沒有遇到任何異常
分析您嘗試創建環境文件的問題,如果是因為您使用類來讀取文件,則必須在其構造函數中執行此操作(請記住使引用為self)並實例化以便能夠訪問它的值,你可以完美地使用一個函數來執行這個閱讀,記住訪問結果可以被視為字典
配置文件名=(config.ini)
[DEFAULT]
ANY = ANY
[Ysl_Leader]
YSL_LEADER = 192
[OTHER]
VALUE = value_config
# using classes
class Cenv(object):
"""
[use the constructor to start reading the file]
"""
def __init__(self):
self.config = configparser.ConfigParser()
self.config.read('config.ini')
# using functions
def Fenv():
config = configparser.ConfigParser()
config.read('config.ini')
return config
def main():
# to be able to access it is necessary to instantiate the class
instance = Cenv()
cfg = instance.config
# access the elements using the key (like dictionaries)
print(cfg['Ysl_Leader']['YSL_LEADER'])
print(cfg['OTHER']['VALUE'])
# call function and assign returned values
cfg = Fenv()
print(cfg['Ysl_Leader']['YSL_LEADER'])
print(cfg['OTHER']['VALUE'])
# in the case of django assign values in module settings
if __name__ == '__main__':
main()
你可以解釋如下結果(字典)
{
"Ysl_Leader": {
"YSL_LEADER": "192"
},
"OTHER": {
"VALUE": "value_config"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.