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.

2

1 Answer 1

-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>")

Sign up to request clarification or add additional context in comments.

1 Comment

const isn't accepted as a parameter unless nargs='?' or action='store_const'. In both cases you also want a default.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.