How do I check if the flag --load is present?
#!/usr/bin/env python3
import argparse
import os
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-l', '--load', nargs='?', metavar='path', help='Load all JSON files recursively in path')
args = parser.parse_args()
print(args)
Calling the script with --load outputs the following:
Namespace(load=None)
I can't omit nargs='?' and use action='store_true' as I'd like to allow an argument to be passed, for example --load abcxyz.
Adding action='store_true'and nargs='?' produces an error of:
parser.add_argument('-l', '--load', nargs='?', metavar='path', help='Load all JSON files recursively in path', action='store_true')
File "/usr/lib/python3.6/argparse.py", line 1334, in add_argument
action = action_class(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'nargs'
You can use the in operator to test whether an option is defined for a (sub) command. And you can compare the value of a defined option against its default value to check whether the option was specified in command-line or not.
#!/usr/bin/env python3
import argparse
import os
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-l', '--load',
dest='load', nargs='?', default=None,
help='Load all JSON files recursively in path')
args = parser.parse_args()
'some_non_exist_option' in args # False
'load' in args # True
if args.load is not None:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With