0

I would like to pass in arguments to this sampleCode.py file.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--num_epochs', '-n', default=2, type=int)
parser.add_argument('--directory', default='/some/string/')
parser.add_argument('--exclude_hydro', default=False, action='store_true')

args = parser.parse_args()
print(args.num_epochs)    # 2
print(args.exclude_hydro) # False

The following commands work for int and string arguments, but not for boolean.

$python3 sampleCode.py -n3                      #args.num_epochs=3
$python3 sampleCode.py --num_epochs 3           #args.num_epochs=3
$python3 sampleCode.py --directory /new/string  #args.directory = /new/string
$python3 sampleCode.py --exclude_hydro True     #error

How can I pass in boolean arguments? I have tried type=bool as a parameter for .add_argument() but that doesn't work.

tamtam
  • 641
  • 9
  • 24

1 Answers1

-1

parser.add_argument('--exclude-hydro', const=True) should work.

Note that you should also be defining help="<help_text>" so that when a user calls the application without any arguments, help text is displayed describing the purpose of each argument:

parser.add_argument('--exclude-hydro', const=True, help="<help_text>")

rst-2cv
  • 1,130
  • 1
  • 15
  • 31
  • `const` isn't accepted as a parameter unless `nargs='?'` or `action='store_const'`. In both cases you also want a `default`. – hpaulj May 25 '18 at 04:34