使用配置文件时,python 命令行参数 'default' 的等效项是什么?

What is the equvalent of python command-line argument 'default' when using config file?

我有以下用于 python 脚本的命令行参数:

command_parser.add_argument("--wateva", help="Don't care.", default=42)

现在我需要从命令行参数切换到配置文件,因为脚本已经变大了,不可能在没有错字的情况下传递所有参数。

如何为从 Python 中的配置文件读取的参数附加默认值(即 config = configparser.ConfigParser()

可以通过将默认值作为字典传递给 ConfigParser 构造函数来指定默认值。

import ConfigParser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')

print config.get('Section1', 'foo') # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print config.get('Section1', 'foo') # -> "Life is hard!"