如何使用 python configparser 模块解析 ini 文件中没有值的标签?
比如我有下面的ini,需要解析rb。在某些 ini 文件中, rb 具有整数值,而在某些文件中根本没有值,如下例所示。如何使用 configparser 做到这一点而不会出现 valueerror?我使用 getint 函数
[section]
person=name
id=000
rb=
如何使用 python configparser 模块解析 ini 文件中没有值的标签?
比如我有下面的ini,需要解析rb。在某些 ini 文件中, rb 具有整数值,而在某些文件中根本没有值,如下例所示。如何使用 configparser 做到这一点而不会出现 valueerror?我使用 getint 函数
[section]
person=name
id=000
rb=
allow_no_value=True
创建解析器对象时需要设置可选参数。
也许使用一个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')]
而不是使用getint()
,使用get()
将选项作为字符串获取。然后自己转换为 int:
rb = parser.get("section", "rb")
if rb:
rb = int(rb)
由于关于 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 和 value 返回一个空白字符串,每个人都很高兴。
为什么不注释掉这样的rb
选项:
[section]
person=name
id=000
; rb=
然后使用这个很棒的 oneliner:
rb = parser.getint('section', 'rb') if parser.has_option('section', 'rb') else None