3

I cant see m to figure out how to iterate over the accepted args of argparse. I get I can iterate over the parsed_args result, but what I want is to iterate over the arguments the parser is configured with ( ie with optparse you can iterate over the args ).

for example:

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

for arg in parser.args():
    print arg

would result in

--a
--b
--c
ByteMe95
  • 836
  • 1
  • 6
  • 18

3 Answers3

8

You'll probably want to getattr from the args:

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

Result:

a None
c None
b None
l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • I specifically said NOT from a parse_args() call – ByteMe95 Mar 14 '17 at 13:19
  • @user136109: Where have you specifically mentioned that? – l'L'l Mar 14 '17 at 15:29
  • For `add_argument('--foo-bar')`, this gives `foo_bar` instead of the acceptable `--foo-bar`. – antak Feb 10 '20 at 11:01
  • @antak: To handle that scenario use `dest`, for example: `parser.add_argument( '--foo-bar', dest='foo-bar')`. The default behavior of `argparse` is to strip away intermediate hyphens. Explanation here: https://docs.python.org/dev/library/argparse.html#dest – l'L'l Feb 10 '20 at 11:21
3

If you want to list the optionals you can do it this way:

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)

I don't see a practical reason to iterate over them however. You can always see the options via --help.

Mariy
  • 5,746
  • 4
  • 40
  • 57
  • Thanks, thats what I have done so far, reaching into the internals which I was hoping to avoid. I want to be able to have an optional UI dialog popup to enter args. In order to do that i need programmatic access to the args – ByteMe95 Mar 14 '17 at 13:20
1

A bit late to the game here, but I found a way to do this without reading from private variables by using a custom help formatter that collects the arguments it is asked to format.

The following program will print ['-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()
Clukester
  • 132
  • 1
  • 8