简体   繁体   English

使用configparser从ini填充类

[英]populate class from ini using configparser

I am newbie with python , started to write some system administration utility that should read info from INI file 我是python的新手,开始编写一些应从INI文件读取信息的系统管理实用程序

Now i need to init a class based of ini sections , my question how can i do that send all infoe parameters key val with following example 现在我需要初始化一个基于ini部分的类,我的问题是如何发送带有以下示例的所有infoe参数key val

Please advice Thanks 请指教谢谢

 class FopsTest():
    def __init__(self,**kwargs):
        self.variables = kwargs

   def set_foptype(self,FILEOP):
       self.variables['FILEOP'] = FLOPTYPE

cfgfile = os.getcwd() +'\wtrconfig.cfg'
config = configparser.ConfigParser()
try:
    os.path.exists(cfgfile)
    config.sections()
    config.read(cfgfile)
  test = FopsTest(<pass ini key,val?>)

You should read the documentation for the configparser module , it does a decent job explaining things. 您应该阅读configparser模块的文档 ,它在解释事情方面做得不错。 Be sure to read the docs for the version of Python 3 you are using though, as the interface seems to have been extended quite a bit between versions. 不过,请务必阅读您正在使用的Python 3版本的文档,因为接口在版本之间似乎已经扩展了很多。

Starting in Python 3.2, it is possible to treat a ConfigParser instance as if it was a Python dictionary (the term used in the docs is the "mapping protocol"). 从Python 3.2开始,可以将ConfigParser实例视为Python字典(在文档中使用的术语是“映射协议”)。 That means, you can probably just create a class instance with FopsTest(**config) , or perhaps FopsTest(**config["TheSectionICareAbout"]) if you only want the items from a specific section of the file. 这意味着,如果您只想要文件的特定部分中的项目,则可以仅使用FopsTest(**config)FopsTest(**config["TheSectionICareAbout"])创建类实例。 See this section of the docs for details. 有关详细信息,请参见文档的本部分

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

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