The python's argparse errors
Asked Answered
S

5

10

where report this error : TypeError: 'Namespace' object is not iterable

import argparse

def parse_args():
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument('-a', '--aa', action="store_true", default=False)
    parser.add_argument('-b', action="store", dest="b")
    parser.add_argument('-c', action="store", dest="c", type=int)

    return parser.parse_args()

def main():
    (options, args) = parse_args()

if __name__ == '__main__':
    main()
Sclerous answered 29/9, 2013 at 10:15 Comment(1)
Before opening a question you should at least skim through the documentation of a module/package. In particular the first example of usage clearly shows that you should do args = parser.parse_args() instead of options, args = parser.parse_args() as you would do with older modules.Celestial
K
15

Your issue has to do with this line:

(options, args) = parse_args()

Which seems to be an idiom from the deprecated "optparse".

Use the argparse idiom without "options":

import argparse
parser = argparse.ArgumentParser(description='Do Stuff')
parser.add_argument('--verbosity')
args = parser.parse_args()
Kennethkennett answered 26/11, 2014 at 19:50 Comment(0)
V
4

Try:

args = parse_args()
print args

Results:

$ python x.py -b B -aa
Namespace(aa=True, b='B', c=None)
Vend answered 29/9, 2013 at 10:18 Comment(0)
C
1

It's exactly like the error message says: parser.parse_args() returns a Namespace object, which is not iterable. Only iterable things can be 'unpacked' like options, args = ....

Though I have no idea what you were expecting options and args, respectively, to end up as in your example.

Chirp answered 29/9, 2013 at 10:44 Comment(0)
P
1

The error is in that parse_argv option is not required or used, only argv is passed.

Insted of:

(options, args) = parse_args()

You need to pass

args = parse_args()

And the rest remains same. For calling any method just make sure of using argv instead of option.

For example:

a = argv.b
Pertinacious answered 21/10, 2017 at 11:52 Comment(0)
T
0

The best way (for me) to operate on args, where args = parser.parse_args() is using args.__dict__. It's good, for example, when you want to edit arguments. Moreover, it's appropriate to use long notation in your arguments, for example '--second' in '-a' and '--third' in '-b', as in first argument.

If you want to run 'main' you can should miss 'options', but it was said earlier.

Thermoluminescent answered 17/2, 2022 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.