1

I'm using argparse for my Python CLI as follows:

import argparse

parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--myarg', type=str, help="Dummy arg")
args = parser.parse_args()

# access with dot notation
print(args.myarg)

This works fine. However, I now want to add an argument called --continue. Trying to access the arg with args.continue gives me a syntax error.

Is there any other way to access CLI args other than the dot notation? I tried dict-like access args['continue'] but that gives me TypeError: 'Namespace' object is not subscriptable. Do I really have to think of another CLI arg name?

stefanbschneider
  • 5,460
  • 8
  • 50
  • 88
  • 1
    You get the syntax error because 'continue' is a reserved word in python. The dot syntax requires that the argument name be a valid python variable name. – hpaulj Aug 05 '20 at 18:46
  • 1
    With the `dest` parameter you can specify a different arg name while still allowing your users to use '--continue'. `metavar` gives even more control over the help display. You are never forced to use an awkward argument name. – hpaulj Aug 06 '20 at 16:48
  • True, that's a good hint about the `dest` parameter - I forgot about that. – stefanbschneider Aug 07 '20 at 07:29

1 Answers1

4

Using vars() returns a dictionary form of an object (like args), letting you do exactly what you tried.

args = vars(parser.parse_args())

print(args['continue'])

Alternatively, you can get the attribute from the object directly with the getattr builtin function:

args = parser.parse_args()

print(getattr(args, 'continue')
Zaxutic
  • 91
  • 2