Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse check if flag is present while also allowing an argument

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'
like image 827
Chris Stryczynski Avatar asked Mar 04 '26 07:03

Chris Stryczynski


1 Answers

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:   
    ...
like image 58
Benjamin Du Avatar answered Mar 07 '26 17:03

Benjamin Du



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!