【问题标题】:Argparse won't parse any arguments I pass in the command lineArgparse 不会解析我在命令行中传递的任何参数
【发布时间】:2018-12-31 00:33:36
【问题描述】:

我正在尝试在终端中运行我的程序:

py program.py -t

并且它没有将布尔值设置为 False。据我所知,我所有的代码看起来都是正确的。

isTitle = True

a = argparse.ArgumentParser(prog='program.py', usage='%(prog) [options]', description='The fooiest of bar')
a.add_argument('-t', '--title', action='store_const', const=False, dest='isTitle', help='show title')
r = a.parse_args()

我在 parse_args 之后有一个语句,它打印 isTitle 布尔值以验证它是否已设置,并且它始终返回 True。你们有什么建议吗?如果需要,我可以添加更多代码/诊断语句。谢谢!

【问题讨论】:

  • 我鼓励海报打印parse_args返回的Namespaceprint(r)。这可以最清楚地了解解析器在做什么。

标签: python python-3.x command-line-interface argparse


【解决方案1】:

dest='isTitle' 并不意味着名为isTitle变量 将被更改,它意味着该值将存储在r.isTitle 中,即在parse_args 调用返回的对象中. argparse 修改全局范围内的任何变量都是疯狂的。

你想要的很简单:

a.add_argument('-t', '--title', action='store_true', dest='isTitle', help='show title')
r = a.parse_args()
print(r.isTitle)

【讨论】:

    猜你喜欢
    • 2013-09-13
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2021-10-10
    • 2012-03-12
    相关资源
    最近更新 更多