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()
1
  • 4
    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. Commented Sep 29, 2013 at 10:20

5 Answers 5

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()
Sign up to request clarification or add additional context in comments.

Comments

4

Try:

args = parse_args()
print args

Results:

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

Comments

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.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.