【问题标题】:Can't solve Python argparse error 'object has no attribute'无法解决 Python argparse 错误“对象没有属性”
【发布时间】:2014-04-22 03:18:12
【问题描述】:

当我运行这段代码时,我得到了

AttributeError: 'ArgumentParser' object has no attribute 'max_seed'

这是代码

import argparse
import ConfigParser

CFG_FILE='/my.cfg'

# Get command line arguments
args = argparse.ArgumentParser()
args.add_argument('verb', choices=['new'])
args.add_argument('--max_seed', type=int, default=1000)
args.add_argument('--cmdline')
args.parse_args()

if args.max_seed:
    pass

if args.cmdline:
    pass

我的源文件名为“fuzz.py”

【问题讨论】:

    标签: python argparse


    【解决方案1】:

    您应该首先初始化解析器和参数,然后才能从 parse_args() 获取实际参数(请参阅文档中的 example):

    import argparse
    import ConfigParser
    
    CFG_FILE='/my.cfg'
    
    # Get command line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('verb', choices=['new'])
    parser.add_argument('--max_seed', type=int, default=1000)
    parser.add_argument('--cmdline')
    
    args = parser.parse_args()
    if args.max_seed:
        pass
    
    if args.cmdline:
        pass
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      如果您在另一个类中使用 argparse 解析参数(在某处使用 self.args = parser.parse_args() ),您可能需要明确告诉您的 lint 解析器忽略 Namespace 类型检查。正如@fransAvoid Pylint warning E1101: 'Instance of .. has no .. member' for class with dynamic attributes 所说:

      只是为了提供现在对我有用的答案 - 作为 [The Compiler][1] 建议您可以为有问题的类添加规则 你的项目.pylintrc:

      [TYPECHECK]
      ignored-classes=Namespace
      

      [1]:https://stackoverflow.com/users/2085149/the-compiler

      【讨论】:

        猜你喜欢
        • 2019-03-15
        • 2022-01-16
        • 1970-01-01
        • 2019-09-08
        • 2020-10-25
        • 2014-05-14
        • 1970-01-01
        • 2020-02-09
        • 1970-01-01
        相关资源
        最近更新 更多