简体   繁体   中英

Using dictionary comprehension with ConfigParser

With the following example, I'm able to get the values from [section1] . How I can do this for the other sections, or for more sections?

store.config

[section1]
field_a = hello
field_b = galaxy

[section2]
field_a = hello
field_b = galaxy

[section3]
field_a = hello
field_b = galaxy

mainfile.py

from ConfigParser import SafeConfigParser

class Main:

   def get_properties(self, section, *variables):
        cfgFile = 'c:\store.config'
        parser = SafeConfigParser()
        parser.read(cfgFile)
        properties= variables
        return {
            variable: parser.get(section,variable) for variable in properties
        }

   def run_me(self):
        config_vars= self.get_properties('section1','field_a')
        print config_vars

op=Main()
op.run_me()

current output:

{'section1': 'field_a'}

This will help me improve the solution given at the post Using var from from function A to function B .

I believe you're looking for the sections method of your SafeConfigParser . For your example, it should return ['section1', 'section2', 'section3'] , which you can iterate over.

Solution:

def run_me(self):
    config_vars= self.get_properties('services','package_install','package_info')
    convig_vars_2 = self.get_properties('network','proxy_server','proxy_user')

Simply as that.

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