0

I have few methods in a class, and I want to allow the user to run their desired methods only by parsing the method name, but I'm stuck at the argparser code, would like to ask for advices here

Basically I want to accomplish something like below

python3 test.py -ip 10.10.10.100 -op method1 method2 method3 ...

in my code

class myClass(parentClass):
    def __init__(self) -> None:
        """
        Setup target system
        """
        try:
            super().__init__()

            self.parser = argparse.ArgumentParser()
            self.parser.add_argument('-ip', help='IP address of target system')
            self.parser.add_argument('-op', help='User desired options')
            self.args, unknown = self.parser.parse_known_args()
        except Exception as exp:
            print(f'Error: {exp}')
    
    def method1(self):
        pass

    def method2(self):
        pass

    def run_prog(self):
        # append user desired method into a list?
        # loop through the list and execute each method
        for i in the_list:
            fn = getattr(self, i)
            fn()

*I have to put argparse in __init__ to follow my org standardization

Marius ROBERT
  • 426
  • 4
  • 15
hellojoshhhy
  • 855
  • 2
  • 15
  • 32
  • I was about to suggest sys.argv, but I suppose your organization prefers to use argparser – Jonathan Taylor May 31 '22 at 07:39
  • @JonathanTaylor I was trying sys.argv, per my understanding, it depends on the position such as `sys.argv[3:]`, but there could be other flag in front the `-op` flag and make the position (index) changed, perhaps you could suggest another way round? – hellojoshhhy May 31 '22 at 07:59

1 Answers1

2

What about adding the nargs='+' option when declaring the -op argument parser?

self.parser.add_argument('-op', help='User desired options', nargs='+')

Martin Tovmassian
  • 1,010
  • 1
  • 10
  • 19