[英]AttributeError: namespace object has no attribute 'accumulate'
这是我当前的代码:
parser = argparse.ArgumentParser(description='Optic disc segmentation.')
parser.add_argument('-f', dest='file', action='store', type=str, help='The image to process.')
args = parser.parse_args()
print(args.accumulate(args.integers))
我一直在最后一行收到此错误:
AttributeError: 'Namespace' object has no attribute 'accumulate'
看来您直接复制了argparse 示例,但不了解用法:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
parse_args
方法创建了一个Namespace
object,用于存储之前调用add_argument
的属性:
ArgumentParser.parse_args(args=None, namespace=None)
将参数字符串转换为对象并将它们分配为命名空间的属性。 返回填充的命名空间。
示例中的args
具有accumulate
和integers
的原因是因为之前对add_argument
的 2 次调用:一个位置参数“整数”和一个可选的dest='accumulate'
。 它们不是 parse_args 返回的parse_args
的内置方法。 它们取决于对add_argument
的调用。
在您的示例中:
parser = argparse.ArgumentParser(description='Optic disc segmentation.')
parser.add_argument('-f', dest='file', action='store', type=str, help='The image to process.')
args = parser.parse_args()
您只使用dest='file'
参数对add_argument
进行了 1 次调用,因此args
将只有一个file
属性,该属性应包含传递给-f
选项的任何内容。
>>> import argparse
>>> parser = argparse.ArgumentParser(description='Optic disc segmentation.')
>>> parser.add_argument('-f', dest='file', action='store', type=str, help='The image to process.')
>>> args = parser.parse_args()
>>> args
Namespace(file=None)
所以,唯一要打印的是print(args.file)
当你调用它时会得到一个值
$ python test.py -f "/path/to/some/file"
/path/to/some/file
我建议查看add_argument
方法中的更多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.