Search code examples
pythonoptparse

Using a file to store optparse arguments


I've been using optparse for a while now, and would like to add the ability to load the arguments from a config file.

So far the best I can think of is a wrapper batch script with the arguments hardcoded... seems clunky.

What is the most elegant way to do this?


Solution

  • I agree with S.Lott's idea of using a config file, but I'd recommend using the built-in ConfigParser (configparser in 3.0) module to parse it, rather than a home-brewed solution.

    Here's a brief script that illustrates ConfigParser and optparse in action.

    import ConfigParser
    from optparse import OptionParser
    
    CONFIG_FILENAME = 'defaults.cfg'
    
    def main():
        config = ConfigParser.ConfigParser()
        config.read(CONFIG_FILENAME)
    
        parser = OptionParser()
        parser.add_option("-l",
                          "--language",
                          dest="language",
                          help="The UI language",
                          default=config.get("Localization", "language"))
        parser.add_option("-f",
                          "--flag",
                          dest="flag",
                          help="The country flag",
                          default=config.get("Localization", "flag"))
    
        print parser.parse_args()
    
    if __name__ == "__main__":
        main()
    

    Output:

    (<Values at 0x2182c88: {'flag': 'japan.png', 'language': 'Japanese'}>, [])
    

    Run with "parser.py --language=French":

    (<Values at 0x2215c60: {'flag': 'japan.png', 'language': 'French'}>, [])
    

    Help is built in. Run with "parser.py --help":

    Usage: parser.py [options]
    
    Options:
      -h, --help            show this help message and exit
      -l LANGUAGE, --language=LANGUAGE
                            The UI language
      -f FLAG, --flag=FLAG  The country flag
    

    The config file:

    [Localization]
    language=Japanese
    flag=japan.png