【问题标题】:Iterating over accepted args of argparse迭代 argparse 的已接受参数
【发布时间】:2017-03-13 21:53:28
【问题描述】:

我看不到 m 来弄清楚如何迭代 argparse 的 accepted 参数。我知道我可以迭代 parsed_args 结果,但我想要的是迭代解析器配置的参数(即使用 optparse 你可以迭代 args )。

例如:

parser = argparse.ArgumentParser( prog = 'myapp' )
parser.add_argument( '--a',  .. )
parser.add_argument( '--b',  ...) 
parser.add_argument( '--c',  ... )

for arg in parser.args():
    print arg

会导致

--a
--b
--c

【问题讨论】:

标签: python


【解决方案1】:

您可能想从args 发送getattr

args = parser.parse_args()
for arg in vars(args):
     print arg, getattr(args, arg)

结果

a None
c None
b None

【讨论】:

  • 我特别说不是来自 parse_args() 调用
  • @user136109:你在哪里特别提到过?
  • 对于add_argument('--foo-bar'),这给出了foo_bar,而不是可接受的--foo-bar
  • @antak:要处理这种情况,请使用dest,例如:parser.add_argument( '--foo-bar', dest='foo-bar')argparse 的默认行为是去掉中间连字符。此处说明:docs.python.org/dev/library/argparse.html#dest
【解决方案2】:

如果你想列出可选项,你可以这样做:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')
parser.add_argument('--baz')
for option in parser._optionals._actions:
    print(option.option_strings)

但是,我没有看到迭代它们的实际理由。您可以随时通过--help查看选项。

【讨论】:

  • 谢谢,这就是我迄今为止所做的,深入到我希望避免的内部。我希望能够有一个可选的 UI 对话框弹出来输入 args。为此,我需要以编程方式访问 args
【解决方案3】:

这里的游戏有点晚了,但我找到了一种方法,无需从私有变量中读取,方法是使用自定义帮助格式化程序收集要求格式化的参数。

以下程序将打印['-h', '--help', '--a', '--b', '--c']

import argparse


class ArgCollector(argparse.HelpFormatter):
    # Will store the arguments in a class variable since argparse uses a class
    # name, not an instance of a class
    args = []

    def add_argument(self, action):
        # Just remember the options
        self.args.extend(action.option_strings)


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('--a')
    parser.add_argument('--b')
    parser.add_argument('--c')

    # Install our new help formatter, use it, then restore the original
    # formatter
    original_formatter_class = parser.formatter_class
    parser.formatter_class = ArgCollector
    parser.format_help()
    parser.formatter_class = original_formatter_class

    # Print the args that argparse would accept
    print(ArgCollector.args)


if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 2021-07-15
    • 2019-09-14
    • 2017-12-22
    • 2019-03-12
    • 2017-06-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多