'The python's argparse errors

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()


Solution 1:[1]

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()

Solution 2:[2]

Try:

args = parse_args()
print args

Results:

$ python x.py -b B -aa
Namespace(aa=True, b='B', c=None)

Solution 3:[3]

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.

Solution 4:[4]

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

Solution 5:[5]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2688272
Solution 2 Robᵩ
Solution 3 Karl Knechtel
Solution 4 Stepan Novikov
Solution 5 zarooba