小编Cam*_*lon的帖子

argparse 参数解析器的子类化

我正在尝试编写一个从 Python argparse ArgumentParser 类派生的解析器类。以下代码的轮廓在命令行上运行良好,但会生成一个错误,我在模块的上下文中很难理解。

代码(稍微精简以删除不重要的东西)如下:

class SansParser(argparse.ArgumentParser):
"""Argument parser for preparing a SansModel fit or calculation

"""

def __init__(self):
    """Initialisation method for the parser class"""

    argparse.ArgumentParser.__init__(self)


    # Subparsers for the two commands 'calc' and 'fit'
    self.subparsers = self.add_subparsers()
    self.fit_parser = self.subparsers.add_parser('fit', help="Fit a dataset")
    self.fit_parser.add_argument('-d', '-data', '-dataset', type = str,
                                 dest = 'dataset',
                                 help = "The dataset to fit in SasXML format")
    self.fit_parser.set_defaults(func=fit)
    self.calc_parser = self.subparsers.add_parser('calc', prog='test')
    self.calc_parser.set_defaults(func=calculate)
Run Code Online (Sandbox Code Playgroud)

我可以将其作为脚本运行,这很好。如果我从 shell 运行它或导入 python 命令行并尝试实例化我得到的类:

$ python sansmodel.py
    Traceback (most recent …
Run Code Online (Sandbox Code Playgroud)

python derived-class argparse

3
推荐指数
1
解决办法
5657
查看次数

标签 统计

argparse ×1

derived-class ×1

python ×1