Разбор аргументов, чтобы они находились в отдельных пространствах имен - PullRequest
0 голосов
/ 21 января 2020

Я хотел бы сделать что-то вроде этого:

import SomeParser


class A1

    @staticmethod
    def SetParser(parser):
        # add my name space and arguments to it
        p = parser.addNameSpace('A1')
        p.add_argument('--foo')
        p.add_argument('--loop_count', 1)  

    def __init__(self, config):
        #get my config section, and set locals from it
        self.myConfig = config['A1']
        self.loopCount = self.myConfig['loop_count']
        if 'foo' in self.myConfig.keys():
            self.foo = True
        else:
            self.foo = False


class B2

    @staticmethod
    def SetParser(parser):
        # add my name space and arguments to it
        p = parser.addNameSpace('B2')
        p.add_argument('--bar')
        p.add_argument('--loop_count', 1)  

    def __init__(self, config):
        #get my config section, and set locals from it
        self.myConfig = config['B2']
        self.loopCount = self.myConfig['loop_count']
        if 'bar' in self.myConfig.keys():
            self.bar = True
        else:
            self.bar = False        


def main():   
    # init parser, and set options   
    parser = SomeParser.parser()
    parser.add_argument('--config_file', 1)
    A1.SetParser()
    B2.SetParser()

    defaultConfig = {'A1','B2'}    
    defaultConfig['A1'] = {'loop_counter': 400, 'foo'}  
    defaultConfig['B2'] = {'loop_counter': 200}

    # ReadConfig will read a config file and return a multi leveled dict like the default one 
    # then use that to override the default values
    defaultConfig.update(ReadConfig(parser.getConfig()['config_file']))

    # send the defaults + read values to the parser, then add the CLI args to that to get final values
    parser.setDefaults(defaultConfig)
    # TODO: add os environment vars here as well
    parser.parseArgs()

    # init the classes  
    a = A1(parser.getConfig())
    b = B2(parser.getConfig())

    # Do some work here

"MyApp --help" должен вывести что-то вроде этого:

usage: MyApp.py [-h] [--config_file file]

optional arguments:
  -h, --help       show this help message and exit
   --config_file file File to fetch configuration from

  A1:
  --foo
  --loop_counter n Number of loop to count

  B2:
  --bar
  --loop_counter n Number of loop to count**

У меня есть все, кроме парсера, не могу найти тот, который даст мне сегментированные варианты. Argpars parent позволит мне получить один или другой аргумент класса, но не оба. Просто нет парсера, который кажется подходящим, я собираюсь написать свой, но было бы неплохо, если бы был тот, который соответствовал бы требованиям, или был ближе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...