python argparse module AttributeError

Question:

I’m learning the argparse module, and I wrote code as follows:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
               help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
               const=sum, default=max,
               help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

I saved it as argparse.py, but when I run it in cmd, it shows:

AttributeError: ‘module’ object has no attribute ‘ArgumentParser’

what’s the problem? Thank you for your help.

Asked By: evbo

||

Answers:

When you say import in Python, the interpreter runs a search to find a file with that name. It first looks for the file in the current folder and then in other paths, such as, /usr/lib/python.

Therefore, when you’re saying import argparse and naming your script argparse.py, Python takes your file and import it as is.

To avoid this, change the name of your file to something else than argparse.py.

Answered By: Plasma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.