使用嵌入式的argparse在Python3中

2024-06-24 13:40:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个Python模块,它可以被命令行和其他模块使用。 就像这样:

python3 Capacity.py arg1 arg2 arg3
or
>>> capacity.execByString("arg1 arg2 arg3")

我做了一个类(通过一些研究)在代码中获得argparse的结果:

class ArgumentParserError(Exception): pass

class Parseur(ArgumentParser):
    def error(self, msg):
        raise ArgumentParserError(msg)

    def analyze(self, args):

        if type(args) is not list:
            args = args.split() # To work with a String

        try:
            result = self.parse_args(args)
            return True, result
            # Returns True and the namespace if OK
        except ArgumentParserError as err:
            return False, err.args[0]
            # Returns False and the error message if not OK

我是这样用的:

class Capacity():
    def __init__(self):
        self.parser = Parseur()
        # Config the parser

    def execByArguments(*args):
        # Do the job

    def execByString(command):
        isOK, result = self.parser.analyze(command)
        if isOk:
            # Launch execByArguments with the rights args in result
        else:
            # Print error message
            print(result)

    def execFromCommandLine():
        args = self.parser.parse_args()
        # Launch execByArguments with the rights args

if __name__ == "__main__":
    execFromCommandLine()

但有两个主要问题,当然还有一些我还没有发现:

  • 由于split函数具有“spaces”分隔符,因此无法正确解析参数(例如双引号)
  • 使用-h标志关闭程序

我确信把它变成另一个Parseur类是无用的/不好的,而且有一个解决方法。 通过子进程启动模块也不是一个好主意:在这种情况下,我希望获得返回的对象。 你能帮我找到一个很酷的方法来做我想做的事吗? 已经谢谢了。你知道吗

附言:在网上写代码是一件很痛苦的事。你知道吗


Tags: 模块theselfparserifdefwithargs
1条回答
网友
1楼 · 发布于 2024-06-24 13:40:26

你不远了。我会这样做:

class Capacity():
    def __init__(self, argv):
        # take over and store arguments (or process further parsing)
        self.parser = Parseur()
        isOk, result = self.parser.analyze(argv)

def argInputValidation(argv):
    #checking the command line arguments given by user
    #and returning valid argv, otherwise exit program
    #with an error message.
    return argv

if __name__ == "__main__":
    obj = Capacity(argInputValidation(sys.argv[1:]))

相关问题 更多 >