pythonプロファイルの読み書き


@(python)
  • 前言
  • configParser
  • python2 - ConfigParser
  • 基本読み書き
  • パラメータ置換
  • デフォルトパラメータ
  • を使用
  • デフォルトプロファイル
  • を使用
  • python3 - configparser
  • 基本読み書き
  • デフォルトは
  • を返します.
  • パラメータ置換

  • pyYAML
  • jason
  • 参照

  • 前言
    コードの中のコンフィギュレーション項目をコンフィギュレーションファイルに抽出し、コンフィギュレーションを修正する際にコードの修正に関わる必要はなく、狂ったmagic numberに直面することを避け、後期ソフトウェアのメンテナンスを極めて便利にします.
    python自体は、ini形式のプロファイルを読み込むための標準的な構成読み書きモジュールconfigParse(python 2、python 3をconfigparserに変更)を提供します.
    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

    標準ライブラリが提供するモジュールに加えて、サードパーティモジュールpyYAMLでyaml 1式のプロファイルを読み書きできます.
    この文書では、pythonがconfigParserとpyYAMLを介してプロファイルを読み書きする方法について説明します.
    configParser
    Note The ConfigParser module has been renamed to configparser in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
    python 2とpython 3ではこのモジュールが少し異なり、古いコードはツールで変換できます.現在、python 2はプロジェクトで使用されているため、python 2およびpython 3でのモジュールの使用について説明します.
    python2 - ConfigParser
    ConfigParserには、*RawConfigParser*ConfigParser*SafeConfigParserの3つが前者のベースで拡張され、インタフェースには追加のオプションパラメータが提供され、より複雑な機能が提供されます.主な違いは、%(value_name)sのパラメータ置換(value_nameは同じsectionまたは[DEFAULT]の他の変数名である)に反映されます.
    ここで使用するデフォルトのプロファイルdefault.cfgの内容は以下の通りです.
    [DEFAULT]
    default_name = lcd
    
    [Section1]
    an_int = 15
    a_bool = true
    a_float = 3.1415
    baz = fun
    bar = Python
    foo = %(bar)s is %(baz)s!
    name = s1_%(default_name)s   ; DEFAULT section's value

    基本読み書き
    RawConfigParserを使用して、プロファイルの基本的な読み書き操作を実現します.
    import ConfigParser
    
    test_cfg = "./default.cfg"
    config_raw = ConfigParser.RawConfigParser()
    config_raw.read(test_cfg)
    
    #         [DEFAULT]
    defaults = config_raw.defaults()
    print defaults
    
    #     section  value 
    a_float = config_raw.getfloat('Section1', 'a_float')
    print "-- number : %f type is : %s"%(a_float ,type(a_float))
    
    #     section  value 
    #         ,        
    a_float = 2.14159
    config_raw.set('Section1', 'a_float', a_float)
    a_float = config_raw.getfloat('Section1', 'a_float')
    print "-- number : %f type is : %s"%(a_float ,type(a_float))
    
    #              ,        
    print "-- RawConfigParser just get raw value"
    str_foo = config_raw.get('Section1', 'foo')
    print str_foo

    異なるデータ型に対応して、get()を呼び出してプロファイルの元のコンテンツを取得するほか、対応するインタフェース、getint, getbooleanを使用することもできます.ここで、ブール値Trueは1、yes、true、on、Falseは0、no、false、offに対応します.
    実行結果
    OrderedDict([('default_name', 'lcd')])
    -- number : 3.141500 type is : <type 'float'>
    -- number : 2.141590 type is : <type 'float'>
    -- RawConfigParser just get raw value
    %(bar)s is %(baz)s!

    パラメータ置換
    RawConfigParserと比較して、プロファイル内のfoo = %(bar)s is %(baz)s!というフォーマットの変数については、読み込み時に置き換えた値を取得するには、クラスConfigParserまたはSafeConfigParserを使用する必要があります.コードは次のとおりです.
    config = ConfigParser.ConfigParser()
    config.read(test_cfg)
    
    print "-- ConfigParser can get interpolation"
    ## get        raw,raw=1             ,      
    ## raw    0,   0 ,       
    str_foo = config.get('Section1', 'foo', raw=1)
    #   str_foo = config.get('Section1', 'foo', 1)
    print str_foo
    str_foo = config.get('Section1', 'foo')
    print str_foo
    str_foo = config.get('Section1', 'foo', 0)
    print str_foo
    
    print "-- After set a new value"
    str_foo = "%(name)s is %(baz)s!"
    config.set('Section1', 'foo', str_foo)
    str_foo = config.get('Section1', 'foo', 1)
    print str_foo
    str_foo = config.get('Section1', 'foo')
    print str_foo
    
    ## raw=0,       ,         section     default section    
    str_foo = config.get('Section1', 'name')
    print str_foo
    
    ##              vars,
    ##    ,     values  ,    vars  {}     key  
    ##             。
    print "-- use default value if pass by vars={}"
    a_float = config.get('Section1', 'a_float1', vars={'a_float1':'0.01'})
    print "-- number : %f type is : %s"%(float(a_float) ,type(a_float))

    実行結果
    -- ConfigParser can get interpolation
    %(bar)s is %(baz)s!
    Python is fun!
    Python is fun!
    -- After set a new value
    %(name)s is %(baz)s!
    s1_lcd is fun!
    s1_lcd
    -- use default value if pass by vars={}
    -- number : 0.010000 type is : <type 'str'>

    デフォルトのパラメータの使用
    一部の構成パラメータは、プロファイルに設定されていない場合があります.この場合、プログラムには対応するデフォルト値があるはずです.プロファイルが見つからない場合は、構成値を使用します.注意前のセクションの設定vars={}とは異なり、ここではプロファイルを優先的に返す値であり、設定のデフォルト値は返されません.
    次のように
    ##       name : default_name
    config = ConfigParser.ConfigParser({'name' : 'default_name'})
    config.readfp(open('./default.cfg'))
    
    #         ,           
    str_foo = config.get('Section1', 'name')
    print str_foo
    print "-- use default value"
    config.remove_option('Section1', 'name')
    #          ,        
    str_foo = config.get('Section1', 'name')
    print str_foo

    実行結果
    s1_lcd
    -- use default value
    default_name

    デフォルトのプロファイルの使用
    プログラム構成の場合、複数のプロファイルを設定し、システムのデフォルトのプロファイルなど、一定の優先度で対応するプロファイルを使用できます.ユーザーによって異なるプロファイルが使用され、プログラムの実行時にユーザープロファイルのプロファイルパラメータが優先されます.ユーザープロファイルが存在しない場合、または対応するパラメータが設定されていない場合、システムのデフォルトプロファイルのパラメータ値を再読み込みします.ここで、デフォルトのプロファイルは、最初に提供するdefaultです.cfg
    2つのプロファイルを追加します.
    user1.cfg
    [DEFAULT]
    default_name = user1
    
    [Section1]
    name = s1_%(default_name)s   ; DEFAULT section's value

    user2.cfg
    [DEFAULT]
    default_name = user1
    
    [Section1]
    name = s1_%(default_name)s   ; DEFAULT section's value

    パラメータの使用優先度は、user3.cfg > uer2.cfg > user1.cfg > default.cfgの使用によって以下のように実現されることを望んでいる.
    config = ConfigParser.ConfigParser()
    ##          
    ##          raise  
    config.readfp(open('./default.cfg'))
    ##         ,       ,        
    config.read(['./user1.cfg', './user2.cfg', './user3.cfg'])
    # readfp           read,  read     ,   
    # config.read(['./user11111111.cfg', './user22222222.cfg'])
    
    ##            , default   
    an_int = config.getint('Section1', 'an_int')
    print "-- number : %f type is : %s"%(an_int ,type(an_int))
    
    ##             
    str_foo = config.get('Section1', 'name')
    print str_foo

    実行結果
    -- number : 15.000000 type is : <type 'int'>
    s1_user2

    デフォルトファイルは存在する必要があります.実行時にロードに失敗するとエラーが表示されます.他のオプション設定ファイルが見つからない場合は、直接無視します.
    python3 - configparser
    互換性を考慮すると、前のpython 2で実装された3つのクラスはpython 3で依然としてサポートされています.python 2で提供された参照の前節では、python 3の使用について説明します.
    基本読み書き
    python 2との差は少なく、プロファイルをロードした後、get, getintなどのインタフェースでパラメータ値を読み取ることも、dictを読み取るように構成パラメータを読み取ることもできます.
    読み込んだプロファイルiniは以下の通り
    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    
    [bitbucket.org]
    user = hg 
    ;comment
    #comment 
    
    [topsecret.server.com]
    port = 50022
    forwardx11 = no

    インタフェースを使用して上記プロファイルの内容を読み込む
    import configparser
    
    config = configparser.ConfigParser()
    print("- Empty config %s"%config.sections())
    
    print("- Load config file")
    config.read("./example.ini")
    ##      sections list    default
    print("> config sections : %s"%config.sections()) 
    print('bitbucket.org' in config )  ##              section
    print("> Load config file is :")
    
    for section in config.keys():
        print("[{s}]".format(s=section))
        for key in config[section]:
            print("{k} = {v}".format(k=key, v=config[section][key]))
    
    ##     dict         
    print("
    - Get value like dict :user = %s"
    %config['bitbucket.org']['user']) conf_bitbucket = config['bitbucket.org'] print(conf_bitbucket['user']) """ The DEFAULT section which provides default values for all other sections""" print("
    - DEFAULT Section"
    ) ## default section , ... for key in config['bitbucket.org']: print(key) print("> Get default value : forwardx11 = %s
    "
    %config['bitbucket.org']['forwardx11']) ## print("
    - Support datatypes"
    ) forwardx11 = config['bitbucket.org'].getboolean('forwardx11') int_port = config.getint('topsecret.server.com', 'port') float_port = config.getfloat('topsecret.server.com', 'port') print("> Get int port = %d type : %s"%(int_port, type(int_port))) print("> Get float port = %f type : %s"%(float_port, type(float_port)))

    実行結果は次のとおりです.
    - Empty config []
    - Load config file
    > config sections : ['bitbucket.org', 'topsecret.server.com']
    True
    > Load config file is :
    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    [bitbucket.org]
    user = hg
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    [topsecret.server.com]
    port = 50022
    forwardx11 = no
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    
    - Get value like dict :user =  hg
    hg
    
    - DEFAULT Section
    user
    serveraliveinterval
    compression
    compressionlevel
    forwardx11
    > Get default value : forwardx11 = yes
    
    
    - Support datatypes
    > Get int port = 50022 type : 'int'>
    > Get float port = 50022.000000 type : 'float'>

    デフォルトの戻り値
    コンフィギュレーション・パラメータを読み込むときに、コンフィギュレーション・ファイルで指定した値が見つからない場合にデフォルトで返される値を設定します.指定したsectionとdefaultで検索した値が見つからないと、raiseエラーではなく設定したfallbackが直接返されます.
    print("
    - Return Fallback"
    ) print("> Get value user = %s"%(config.get('bitbucket.org', 'user'))) print("> Get value user = %s"%(config.get('bitbucket.org', 'user', fallback="fallback_name"))) print("> Get value forwardx11 = %s"%(config.getboolean('bitbucket.org', 'forwardx11', fallback=False))) print("> Get value forwardx22 = %s"%(config.getboolean('bitbucket.org', 'forwardx22', fallback=False))) print("> Get value user2 = %s"%(config.get('bitbucket.org', 'user2', fallback="fallback_name")))

    実行結果は次のとおりです.
    - Return Fallback
    > Get value user = hg
    > Get value user = hg
    > Get value forwardx11 = True
    > Get value forwardx22 = False
    > Get value user2 = fallback_name

    パラメータ置換
    python 2で説明したパラメータ置換、pyton 3でデフォルトで使用されているBasicInterpolation()は、直接サポートされています.前述したように、変数は同じsection(defaultを含む)でなければなりません.他のsectionのパラメータを使用する場合は、ExtendedInterpolation()を使用する必要があります.文法的には多少異なります.
    次のようにbasic_interpolation.iniはpython 2と同様にベースの置換プロファイルです
    [Paths]
    home_dir: /Users
    my_dir: %(home_dir)s/lumberjack
    my_pictures: %(my_dir)s/Pictures

    次に、パラメータがextended_で異なるsectionを使用できるように拡張します.interpolation.iniでは、置換パラメータの書き方は${section_name: value_name}
    [Common]
    home_dir: /Users
    library_dir: /Library
    system_dir: /System
    macports_dir: /opt/local
    
    [Frameworks]
    Python: 3.2
    path: ${Common:system_dir}/Library/Frameworks/
    
    [Arthur]
    nickname: Two Sheds
    last_name: Jackson
    my_dir: ${Common:home_dir}/twosheds
    my_pictures: ${my_dir}/Pictures
    python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}

    以上の2つのプロファイルを次のコードで読み込みます.
    print("
    - BasicInterpolation"
    ) #default : config = configparser.ConfigParser(interpolation=configparser.BasicInterpolation()) ## interpolation BasicInterpolation() config.read("./basic_interpolation.ini") print("> Get raw value %s"%(config.get('Paths', 'my_dir', raw = 1))) print("> Get value %s"%(config.get('Paths', 'my_dir', raw = 0))) print("
    - ExtendedInterpolation - other sections"
    ) config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation()) config.read("./extended_interpolation.ini") print("> Get raw value %s"%(config.get('Arthur', 'python_dir', raw = 1))) print("> Get value %s"%(config.get('Arthur', 'python_dir', raw = 0)))

    実行結果:
    - BasicInterpolation
    > Get raw value %(home_dir)s/lumberjack
    > Get value /Users/lumberjack
    
    - ExtendedInterpolation - other sections
    > Get raw value ${Frameworks:path}/Python/Versions/${Frameworks:Python}
    > Get value /System/Library/Frameworks//Python/Versions/3.2

    pyYAML
    jason
    リファレンス
  • python2-ConfigParser
  • python3-configparser
  • yaml言語
  • *
    http://www.ruanyifeng.com/blog/2016/07/yaml.html?f=tt ↩