2

I try to build an argparser, where one of the parsers should have a default value, and is also a required. I have the following so far:

   fulllist_parser.add_argument(
    '--type',
    required=True,
    default="VirtualMachine",
    type=str,
    help='Object type, e.g. Network, VirtualMachine.'

When I run it from CLI, I get an error:

 supdeploy fulllist: error: argument --type is required

I see why this is coming up, as I'm not including --type on the CLI. And that is what I want to achieve, that the default is set even if I don't include the parser option on CLI.

Anyway to run this?

derchris
  • 285
  • 4
  • 11
  • 1
    Aren't "required" and "has a default value" mutually exclusive? "the user absolutely must supply a value for this, crash otherwise" vs "if the user does not supply a value for this, that's fine, just use this value" – Kevin Oct 14 '15 at 12:54
  • Doh ;) Why did I not think about it. Thanks for the hint, exactly what I was trying to achieve. – derchris Oct 14 '15 at 12:57
  • Ok, maybe not exactly. As I will not see the help output anymore. – derchris Oct 14 '15 at 12:58

1 Answers1

0

You just have to use default and no required

fulllist_parser.add_argument(
  '--type',
  default="VirtualMachine",
  type=str,
  help='Object type, e.g. Network, VirtualMachine.'

Because then if it isn't specified you get the default value back (so you always get a value). Have a look at the documentation:

The default keyword argument of add_argument(), whose value defaults to None, specifies what value should be used if the command-line argument is not present. For optional arguments, the default value is used when the option string was not present at the command line

TobiMarg
  • 3,667
  • 1
  • 20
  • 25