【问题标题】:What is the equvalent of python command-line argument 'default' when using config file?使用配置文件时,python 命令行参数“默认”的等价物是什么?
【发布时间】:2016-04-16 01:23:02
【问题描述】:

我有以下 Python 脚本的命令行参数:

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

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

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

【问题讨论】:

    标签: python python-3.x command-line-arguments configuration-files


    【解决方案1】:

    可以通过将默认值作为字典传递给 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!"
    

    【讨论】:

    • example.cfg 看起来如何?如何将您的答案用于配置文件中的不同部分?
    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2021-06-19
    • 2018-08-15
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多