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

后端 未结 8 1893
南笙
南笙 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:59

    I can't say it's the best way, but I have an OptionParser class that I made that does just that - acts like optparse.OptionParser with defaults coming from a config file section. You can have it...

    class OptionParser(optparse.OptionParser):
        def __init__(self, **kwargs):
            import sys
            import os
            config_file = kwargs.pop('config_file',
                                     os.path.splitext(os.path.basename(sys.argv[0]))[0] + '.config')
            self.config_section = kwargs.pop('config_section', 'OPTIONS')
    
            self.configParser = ConfigParser()
            self.configParser.read(config_file)
    
            optparse.OptionParser.__init__(self, **kwargs)
    
        def add_option(self, *args, **kwargs):
            option = optparse.OptionParser.add_option(self, *args, **kwargs)
            name = option.get_opt_string()
            if name.startswith('--'):
                name = name[2:]
                if self.configParser.has_option(self.config_section, name):
                    self.set_default(name, self.configParser.get(self.config_section, name))
    

    Feel free to browse the source. Tests are in a sibling directory.

提交回复
热议问题