1

After importing argparse (among others that I needed) I wrote the following piece of code:

parser = argparse.ArgumentParser()
(..some code with optional arguments...)
requiredArguments = parser.add_argument_group("Required arguments")
(..some code with required arguments...)
requiredArguments.add_argument("--extension", "-ext", help="set the extension", type=str)

args = parser.parse_args() 

if args.version:
    print("blahblahblah")
elif args.example:
    print("blahblahblah")
elif args.width:
    screen_width = "%i" % args.width
elif args.height:
    screen_height = "%i" % args.height
elif args.sequence:
    sequence = "%i" % args.sequence
elif args.url:
    url = "%s" % args.url
elif args.ext:
    ext = "%s" % args.ext
else:
    print("blahblahblah")

[Some additional code irrelevant to the case as it is related to screenshots]

And in the following piece of code is where the problem arises:

number = 0

while number < args.sequence:
    url = args.url+str(number)+args.ext

On my terminal I have specified all the necessary arguments (or at least I believe I have):

python script.py -k [keyword] -w [screen_width] -hg [screen_height] -s 10 -u "url" -ext "extension_to_the_url"

Regardless of the positioning of the arguments, of splitting "url = args.url+str(number)+args.ext" in several parts, using and not using brackets, and a long etcetera (as well as also trying "nargs"), the error is the same:

AttributeError: 'Namespace' object has no attribute 'ext'

There must be something wrong with how I'm using the 'ext' argument, because in a previous version of the script where 'ext' was not provided, Python didn't complain at all.

I'm new to Python and I'm running out of ideas. I read there's a bug that shows this error and that basically it means too few arguments were provided? But that would make no sense since all the arguments were provided via command line...

Any ideas?

Thanks in advance!

ccp2809
  • 13
  • 2
  • I think that attribute you should be accessing "extension" and not "ext", If you want "ext" to be the attribute that you need to include the dest parameter. You add 'dest='ext'" to the add_argument call. – Claudio Corsi Apr 07 '21 at 21:08
  • Add a `print(args)` to your code when debugging. That way you can see what the parser did. You'll see a `extension=...` instead of `ext`. – hpaulj Apr 07 '21 at 21:51
  • It's better to use '-e', single dash and single letter for a short flag. `argparse` takes `dest` from the first long flag, eg '--extension'. – hpaulj Apr 07 '21 at 22:09

1 Answers1

0

add dest='ext', like that:

requiredArguments.add_argument("--extension", "-ext", action='store', dest='ext', help="set the extension", type=str)

and use like:

python stack_args_exp.py -ext 23
Vova
  • 3,117
  • 2
  • 15
  • 23