ConfigParser.get 返回字符串,需要转换为节

0 投票
2 回答
2326 浏览
提问于 2025-04-18 17:51

我想把 RawConfigParser.get('somesection', 'someoption') 返回的值当作另一个 RawConfigParser.get 的部分,但实际上得到的结果是一个被双重包裹的字符串。

section = RawConfigParser.get ('somesection', 'someoption')
subsection = RawConfigParser.get (section, 'someotheroption') # INCORRECT RawConfigParser.get ('"somesection"', 'someotheroption')

我该怎么避免这种情况呢?

2 个回答

0

你应该创建一个文件对象,然后使用 RawConfigParser.readfp() 方法。

>>> help(ConfigParser.RawConfigParser.readfp)

Help on method readfp in module ConfigParser:

readfp(self, fp, filename=None) unbound ConfigParser.RawConfigParser method
    Like read() but the argument must be a file-like object.

    The `fp' argument must have a `readline' method.  Optional
    second argument is the `filename', which if not given, is
    taken from fp.name.  If fp has no `name' attribute, `<???>' is
    used.
2

你有几个选择,其中一个是使用ast库。

>>> quoted_string = '"this is a quote"'
>>> quoted_string
'"this is a quote"'
>>> import ast
>>> unquoted_string = ast.literal_eval(quoted_string)
>>> unquoted_string
'this is a quote'

撰写回答