15

python configparserモジュールを使用して、iniファイルに値のないタグを解析するにはどうすればよいですか?

たとえば、次の ini があり、rb を解析する必要があります。以下の例のように、一部の ini ファイルでは rb に整数値が含まれ、一部の ini ファイルではまったく値がありません。valueerrorを取得せずにconfigparserでそれを行うにはどうすればよいですか? getint 関数を使用します

[section]
person=name
id=000
rb=
4

5 に答える 5

13

allow_no_value=Trueパーサー オブジェクトを作成するときに、オプションの引数を設定する必要があります。

于 2010-08-27T18:27:42.380 に答える
7

多分try...exceptブロックを使用します:

    try:
        value=parser.getint(section,option)
    except ValueError:
        value=parser.get(section,option)

例えば:

import ConfigParser

filename='config'
parser=ConfigParser.SafeConfigParser()
parser.read([filename])
print(parser.sections())
# ['section']
for section in parser.sections():
    print(parser.options(section))
    # ['id', 'rb', 'person']
    for option in parser.options(section):
        try:
            value=parser.getint(section,option)
        except ValueError:
            value=parser.get(section,option)
        print(option,value,type(value))
        # ('id', 0, <type 'int'>)
        # ('rb', '', <type 'str'>)
        # ('person', 'name', <type 'str'>) 
print(parser.items('section'))
# [('id', '000'), ('rb', ''), ('person', 'name')]
于 2010-08-27T18:31:28.323 に答える
3

を使用する代わりに、 をgetint()使用get()してオプションを文字列として取得します。次に、自分で int に変換します。

rb = parser.get("section", "rb")
if rb:
    rb = int(rb)
于 2010-08-27T18:47:14.660 に答える
0

Python 2.6 についてはまだ未回答の質問があるため、以下は Python 2.7 または 2.6 で動作します。これは、ConfigParser でオプション、セパレータ、および値を解析するために使用される内部正規表現を置き換えます。

def rawConfigParserAllowNoValue(config):
    '''This is a hack to support python 2.6. ConfigParser provides the 
    option allow_no_value=True to do this, but python 2.6 doesn't have it.
    '''
    OPTCRE_NV = re.compile(
        r'(?P<option>[^:=\s][^:=]*)'    # match "option" that doesn't start with white space
        r'\s*'                          # match optional white space
        r'(?P<vi>(?:[:=]|\s*(?=$)))\s*' # match separator ("vi") (or white space if followed by end of string)
        r'(?P<value>.*)$'               # match possibly empty "value" and end of string
    )
    config.OPTCRE = OPTCRE_NV
    config._optcre = OPTCRE_NV
    return config

使用

    fp = open("myFile.conf")
    config = ConfigParser.RawConfigParser()
    config = rawConfigParserAllowNoValue(config)

サイドノート

Python 2.7 の ConfigParser には OPTCRE_NV がありますが、上記の関数でそれを正確に使用すると、正規表現は vi と value に対して None を返し、ConfigParser が内部的に失敗します。上記の関数を使用すると、vi と値の空白文字列が返され、誰もが満足します。

于 2016-01-25T20:52:25.550 に答える