python - ConfigParser.setdefault() 的用法

标签 python python-3.6 configparser

我试图在实例化后在 configparser.ConfigParser 实例上设置默认值。 在检查实例时,我发现了方法 ConfigParser.setdefault():

Help on method setdefault in module collections.abc:

setdefault(key, default=None) method of configparser.ConfigParser instance
    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

虽然这根本没有多大帮助,但official documentation甚至没有提到这个public方法。

所以我开始尝试错误:

>>> cp.setdefault('asd', 'foo')
<Section: asd>
>>> cp['asd']
<Section: asd>
>>> cp['asd']['foo']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/configparser.py", line 1233, in __getitem__
    raise KeyError(key)
KeyError: 'foo'
>>> cp['foo']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/configparser.py", line 959, in __getitem__
    raise KeyError(key)
KeyError: 'foo'
>>> cp.setdefault('asd', {'foo': 'bar'})
<Section: asd>
>>> cp['asd']
<Section: asd>
>>> cp['asd']['foo']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/configparser.py", line 1233, in __getitem__
    raise KeyError(key)
KeyError: 'foo'
>>> cp['foo']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/configparser.py", line 959, in __getitem__
    raise KeyError(key)
KeyError: 'foo'
>>> 

但我不知道如何使用默认键 'foo' 和值 'bar' 初始化默认部分 'asd' >.

所以我的问题是:

  1. ConfigParser.setdefault() 方法的用途是什么?
  2. 如何在 ConfigParser 实例初始化后设置默认值?

更新
经过进一步调查,发现 ConfigParser.setdefault() 继承自 _collections_abc.MutableMapping

最佳答案

ConfigParser.setdefault与设置 ConfigParser 的默认值无关。如果要设置默认值,请使用 DEFAULT部分,为其他部分提供默认值:

cp['DEFAULT']['key'] = 'value'

或者如果您配置了不同的 default_section ,使用您配置的任何内容。

docs 中所述,

configparser objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the MutableMapping ABC. However, there are a few differences that should be taken into account:

[list of differences, none of which involve setdefault]

setdefault是 MutableMapping 指定的操作之一。 cp.setdefault('asd', 'foo')尝试设置cp['asd'] = 'foo'如果没有 cp['asd'] 的条目,然后返回cp['asd'] .

在 ConfigParser 中,cp['asd'] 的条目将是 'asd'部分,并且设置 cp['asd'] = 'foo' 是不合法的。设置 cp['asd'] 是合法的到映射,但您已经有了 cp['asd']部分,所以你的cp.setdefault('asd', {'foo': 'bar'})调用也没有执行任何操作。

关于python - ConfigParser.setdefault() 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617423/

相关文章:

python - Tensorflow 不更新权重

python - 如何使用 python 3 让数据沿线显示?

python - ConfigObj 或 ConfigParser 哪个更好?

python - Pandas - 在 DataFrame 中的任何位置查找值索引

python - 获取从一个时间到另一个时间的数据

python - os.stat(path).st_mtime 实际上如何获取文件修改时间?

python - 将日志记录配置包含在 configparser 读取的文件中

python - 使用 ConfigParser 替换已存在的字符串时出现问题

python - 同一模型的多个版本的 django 管理页面

sockets - 在git bash中杀死一个进程