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

2
  • I was about to suggest sys.argv, but I suppose your organization prefers to use argparser Commented May 31, 2022 at 7: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? Commented May 31, 2022 at 7:59

1 Answer 1

2

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Cool! Learned something new!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.