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

后端 未结 8 1833
南笙
南笙 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 16:07

    Check out ConfigArgParse - its a new PyPI package (open source) that serves as a drop in replacement for argparse with added support for config files and environment variables.

    0 讨论(0)
  • 2020-12-22 16:09

    I'm using ConfigParser and argparse with subcommands to handle such tasks. The important line in the code below is:

    subp.set_defaults(**dict(conffile.items(subn)))
    

    This will set the defaults of the subcommand (from argparse) to the values in the section of the config file.

    A more complete example is below:

    ####### content of example.cfg:
    # [sub1]
    # verbosity=10
    # gggg=3.5
    # [sub2]
    # host=localhost
    
    import ConfigParser
    import argparse
    
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()
    
    parser_sub1 = subparsers.add_parser('sub1')
    parser_sub1.add_argument('-V','--verbosity', type=int, dest='verbosity')
    parser_sub1.add_argument('-G', type=float, dest='gggg')
    
    parser_sub2 = subparsers.add_parser('sub2')
    parser_sub2.add_argument('-H','--host', dest='host')
    
    conffile = ConfigParser.SafeConfigParser()
    conffile.read('example.cfg')
    
    for subp, subn in ((parser_sub1, "sub1"), (parser_sub2, "sub2")):
        subp.set_defaults(**dict(conffile.items(subn)))
    
    print parser.parse_args(['sub1',])
    # Namespace(gggg=3.5, verbosity=10)
    print parser.parse_args(['sub1', '-V', '20'])
    # Namespace(gggg=3.5, verbosity=20)
    print parser.parse_args(['sub1', '-V', '20', '-G','42'])
    # Namespace(gggg=42.0, verbosity=20)
    print parser.parse_args(['sub2', '-H', 'www.example.com'])
    # Namespace(host='www.example.com')
    print parser.parse_args(['sub2',])
    # Namespace(host='localhost')
    
    0 讨论(0)
提交回复
热议问题