简体   繁体   English

如何将多个函数名称解析为 python 命令行参数?

[英]How to parse multiple function name to python command line arguments?

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我在一个类中的方法很少,我想让用户只通过解析方法名称来运行他们想要的方法,但是我被困在 argparser 代码中,想在这里寻求建议

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 *我必须将 argparse 放入__init__以遵循我的组织标准化

在声明-op参数解析器时添加nargs='+'选项怎么样?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM