Which is the best way to allow configuration options be overridden at the command line in Python?

后端 未结 8 1891
南笙
南笙 2020-12-22 15:13

I have a Python application which needs quite a few (~30) configuration parameters. Up to now, I used the OptionParser class to define default values in the app itself, with

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-22 15:53

    You can use ChainMap

    A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.
    

    You can combine values from command line, environment variables, configuration file, and in case if the value is not there define a default value.

    import os
    from collections import ChainMap, defaultdict
    
    options = ChainMap(command_line_options, os.environ, config_file_options,
                   defaultdict(lambda: 'default-value'))
    value = options['optname']
    value2 = options['other-option']
    
    
    print(value, value2)
    'optvalue', 'default-value'
    

提交回复
热议问题