Why isn't fromfile-prefix-chars in Python argparse working?

前端 未结 4 756
长情又很酷
长情又很酷 2020-12-20 19:36

I\'m trying to use the fromfile-prefix-chars feature of argparse in Python to load all my command line arguments from a file, but it keeps complaining that I haven\'t specif

4条回答
  •  死守一世寂寞
    2020-12-20 20:17

    Try to this way

    # encoding: utf-8
    import imp
    import argparse
    
    
    class LoadConfigAction(argparse._StoreAction):
        NIL = object()
    
        def __init__(self, option_strings, dest, **kwargs):
            super(self.__class__, self).__init__(option_strings, dest)
            self.help = "Load configuration from file"
    
        def __call__(self, parser, namespace, values, option_string=None):
            super(LoadConfigAction, self).__call__(parser, namespace, values, option_string)
    
            config = imp.load_source('config', values)
    
            for key in (set(map(lambda x: x.dest, parser._actions)) & set(dir(config))):
                setattr(namespace, key, getattr(config, key))
    

    Usage

    parser.add_argument("-C", "--config", action=LoadConfigAction, default=None)
    parser.add_argument("-H", "--host")
    

    Example config (real is python file)

    # Config example /etc/my.conf
    import os
    
    # Parameter definition
    host = os.getenv("HOST", "127.0.0.1")
    

提交回复
热议问题