Search code examples
pythonoopcmdcommand-line-interfaceargparse

how can i add new argparse commands in oop python depends on the if statement in the beginning of the class (libs: cmd, argparse)


I have been stuck with this problem for more than 4 days. I made a OOP Python program, which is supposed to be an CLI, so I made a logic of code like this. You use command python3 script.py first to open the first pack of the commands. There are more arguments which you can use. The same for the variant second. The problem is that, when I'm using service1.set_defaults(func=run_first) it is calling this sub function, but it is not adding any variables with new arguments. How can I solve it?

import cmd
import argparse
import sys


class Console(cmd.Cmd):
    def run_first():
        parser = argparse.ArgumentParser(prog="set")
        parser.add_argument('--mode',
                                  help="you can type the mode")
        parser.add_argument('--value',
                                  help="write here a value which you want to use")
        # set argument and its parameters

        def help_set(self):
            self.parser.print_help()

        def do_set(self, line):
            try:
                parsed = self.parser.parse_args(line.split())
                if parsed.mode == 'example1':
                    print(parsed)
                else:
                    print(parsed)
            except SystemExit:
                return
            print("Test1...")

    def run_second():
        print("Just print this")

    try:
        # here are the first arguments which u use in the beginning
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers()

        service1 = subparsers.add_parser('first')
        service1.set_defaults(func=run_first)

        service2 = subparsers.add_parser('second')
        service2.set_defaults(func=run_second)

        args = parser.parse_args()
        args.func()

    except AttributeError:
        print('Seems like u forgot an argument')
        sys.exit()
        
        
        
if __name__ == "__main__":
    cli = Console()
    cli.cmdloop()

What have I already tried:

I was trying to solve it with the flag marker. I made a flag in a global class vision and was calling these sub function, which were editing flag's value and returning it into the main class vision, but it was not working.

I also tried use subparser, but the result is the same.


Solution

  • i solved the problem by making three classes - two for the cmd env and one for the arg parsing the main cause of the problem was my way of the mixing the cmd lib env with argparse also, it is really important to not forget to make first parser part in the def __init__()