【问题标题】:While using Argparse "AttributeError: 'Namespace' object has no attribute 'command'" keeps showing up on terminal使用 Argparse 时,“AttributeError: 'Namespace' object has no attribute 'command'” 不断出现在终端上
【发布时间】:2021-07-03 17:39:46
【问题描述】:

在导入 argparse(以及我需要的其他内容)之后,我编写了以下代码:

parser = argparse.ArgumentParser()
(..some code with optional arguments...)
requiredArguments = parser.add_argument_group("Required arguments")
(..some code with required arguments...)
requiredArguments.add_argument("--extension", "-ext", help="set the extension", type=str)

args = parser.parse_args() 

if args.version:
    print("blahblahblah")
elif args.example:
    print("blahblahblah")
elif args.width:
    screen_width = "%i" % args.width
elif args.height:
    screen_height = "%i" % args.height
elif args.sequence:
    sequence = "%i" % args.sequence
elif args.url:
    url = "%s" % args.url
elif args.ext:
    ext = "%s" % args.ext
else:
    print("blahblahblah")

[Some additional code irrelevant to the case as it is related to screenshots]

问题出在下面的一段代码中:

number = 0

while number < args.sequence:
    url = args.url+str(number)+args.ext

在我的终端上,我已经指定了所有必要的参数(或者至少我相信我有):

python script.py -k [keyword] -w [screen_width] -hg [screen_height] -s 10 -u "url" -ext "extension_to_the_url"

不管参数的位置如何,将“url = args.url+str(number)+args.ext”分成几个部分,使用和不使用括号,以及长等等(以及尝试“ nargs"),错误是一样的:

AttributeError: 'Namespace' object has no attribute 'ext'

我使用 'ext' 参数的方式一定有问题,因为在没有提供 'ext' 的先前版本的脚本中,Python 根本没有抱怨。

我是 Python 新手,我的想法已经不多了。我读到有一个错误显示此错误,基本上这意味着提供的参数太少?但这没有任何意义,因为所有参数都是通过命令行提供的......

有什么想法吗?

提前致谢!

【问题讨论】:

  • 我认为您应该访问“extension”而不是“ext”的属性,如果您希望“ext”成为您需要包含 dest 参数的属性。您将 'dest='ext'" 添加到 add_argument 调用中。
  • 在调试时将print(args) 添加到您的代码中。这样你就可以看到解析器做了什么。您将看到 extension=... 而不是 ext。
  • 短标志最好使用'-e'、单破折号和单字母。 argparse 从第一个长标志中获取dest,例如'--extension'。

标签: python argparse


【解决方案1】:

添加 dest='ext',像这样:

requiredArguments.add_argument("--extension", "-ext", action='store', dest='ext', help="set the extension", type=str)

并像这样使用:

python stack_args_exp.py -ext 23

【讨论】:

    猜你喜欢
    • 2020-10-24
    • 2022-12-03
    • 2022-12-01
    • 2018-03-12
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 2021-07-25
    • 2015-09-26
    相关资源
    最近更新 更多