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

huangapple go评论62阅读模式
英文:

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 a 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")

        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 you 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 you 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 functions, which were editing the flag's value and returning it into the main class vision, but it was not working.

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

英文:

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.

答案1

得分: 1

我通过创建三个类解决了这个问题 - 两个用于 cmd 环境,一个用于参数解析。问题的主要原因是我混合使用了 cmd 库环境和 argparse。同时,不要忘记在 def __init__() 中添加第一个解析器部分非常重要。

英文:

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__()

huangapple
  • 本文由 发表于 2023年5月11日 12:59:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定