gpt4 book ai didi

python - 如何为 SafeConfigParser 设置默认值?

转载 作者:IT老高 更新时间:2023-10-28 21:06:16 25 4
gpt4 key购买 nike

我有一个配置文件如下:

[job]
mailto=bob
logFile=blahDeBlah.txt

我想使用 SafeConfigParser 读取选项:

values = {} 
config = ConfigParser.SafeConfigParser()
try:
config.read(configFile)
jobSection = 'job'

values['mailto'] = config.get( jobSection, 'mailto' )
values['logFile'] = config.get( jobSection, 'logFile' )
# it is not there
values['nothingThere'] = config.get( jobSection, 'nothingThere' )
.... # rest of code

最后一行当然会报错。如何为 config.get() 方法指定默认值?

再一次,如果我有一个选项文件如下:

[job1]
mailto=bob
logFile=blahDeBlah.txt

[job2]
mailto=bob
logFile=blahDeBlah.txt

似乎没有办法为 job1 指定与 job2 部分中的默认选项不同的默认选项。

最佳答案

使用构造函数的defaults参数:

# class ConfigParser.SafeConfigParser([defaults[, dict_type]]) 
#
config = ConfigParser.SafeConfigParser({'nothingThere': 'lalalalala'})
...
...
# If the job section has no "nothingThere", "lalalalala" will be returned
#
config.get(jobSection, 'nothingThere')

关于python - 如何为 SafeConfigParser 设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6107149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com