1

Maybe there was an answer to one of the similar questions, but I couldn't find it.

What I need.

I have a table to read from: table with most recent data (fast), table with data for one day (day).

I want to read from day-table by default and from fast-table if I provide an argument -f in the command line.

Then I have defaults for each argument. So if I don't provide any arguments ("-s" or "-f"), I want to use "day" with the default value. If I use something like "-s 20161001" or "-f 1452557323", I want to use that value. If use "-f", I want to use "-f" default value.

All I have right now is:

table_choice = parser.add_mutually_exclusive_group(required=True)

table_choice.add_argument(
    '-s', '--day-table',
    dest='day',
    help='day table data',
    default="path/" + day(),
)

table_choice.add_argument(
    '-f', '--fast-table',
    dest='fast',
    help='fast table data',
    default=fast(),
)

But sadly it doesn't work like I want. "script -f" returns:

Script: error: argument -f/--fast-table: expected one argument

Only works if I have provided a value.

antonavy
  • 480
  • 6
  • 11

1 Answers1

2

If nargs='?', then you get a 3 way action - the default, a constant, or the value.

table_choice.add_argument(
    '-f', '--fast-table',
    dest='fast',
    help='fast table data',
    default=fast(),
    nargs='?',
    const='value_if_noarg'
)

This nargs plays nicely with mutually exclusive groups (including the 'required' one).

By making the group required, you will have to use either -s or -f. Omit the required=True is you want the option of using neither.

The namespace will have values for both day and fast regardless of what is in the commandline. If you want the day value to have priority of the fast one, choose the defaults so you can distinguish between the default and a given value. The default default None is handy for that.

You could use default=argparse.SUPPRESS to keep a default out of the namespace, but that's harder to test than args.fast is None.

As discussed in Python argparse --toggle --no-toggle flag your arguments could even share the dest. Whether that makes the following logic easier or not is questionable.

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks, just what I needed. Used const and default for "day" and just const for "fast". How did I miss it when reading manuals =) – antonavy Jan 13 '16 at 11:16