2

以下に説明するコードを使用すると、file.cfgに格納されているプロパティを正常に取得できますが、出力を他の変数に使用するにはどうすればよいですか?

from ConfigParser import SafeConfigParser

class Main:

   def get_properties(self, section, *variables):
        cfgFile = 'c:\file.cfg'
        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('database','host','dbname')
        print config_vars

op=Main()
op.run_me()

私はまだPythonを学んでいますが、出力を個々の変数に設定するために何をする必要があるのか​​わかりません。

現在の出力:

{'host': 'localhost', 'dbname': 'sample'} 

私が欲しいもの:

db_host = localhost
db_name = sample
4

2 に答える 2

2
def run_me(self):
     config_vars= self.get_properties('database','host','dbname')
     for key, value in config_vars.items():
         print key, "=", value

dict-objectconfig_varsを受け取ったので、構成変数をdictの値として使用できます。

 >>> print config_vars["dbname"]
 sample
 >>> print config_vars["host"]
 localhost

ドキュメントでPython辞書の詳細を読んでください。

于 2012-10-11T11:51:17.533 に答える
1

私はこのアプローチを提案します:

import ConfigParser
import inspect

class DBConfig:
    def __init__(self):
        self.host = 'localhost'
        self.dbname = None

    def foo(self): pass

class ConfigProvider:
    def __init__(self, cfg):
        self.cfg = cfg

    def update(self, section, cfg):
        for name, value in inspect.getmembers(cfg):
            if name[0:2] == '__' or inspect.ismethod(value):
                continue

            #print name
            if self.cfg.has_option(section, name):
                setattr(cfg, name, self.cfg.get(section, name))

class Main:
    def __init__(self, dbConfig):
        self.dbConfig = dbConfig

    def run_me(self):
        print('Connecting to %s:%s...' % (self.dbConfig.host, self.dbConfig.dbname))


config = ConfigParser.RawConfigParser()
config.add_section('Demo')
#config.set('Demo', 'host', 'domain.com')
config.set('Demo', 'dbname', 'sample')

configProvider = ConfigProvider(config)

dbConfig = DBConfig()
configProvider.update('Demo', dbConfig)

main = Main(dbConfig)
main.run_me()

アイデアは、クラス内のすべての重要なプロパティを収集することです(デフォルトを設定することもできます)。

次に、メソッドConfigProvider.update()はそれらを構成の値で上書きします(存在する場合)。

obj.nameこれにより、簡単な構文でプロパティにアクセスできます。

要旨

于 2012-10-11T12:13:20.537 に答える