Chris Stryczynski
Chris Stryczynski

Reputation: 33921

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'

Upvotes: 3

Views: 5615

Answers (2)

Benjamin Du
Benjamin Du

Reputation: 1891

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:   
    ...

Upvotes: 3

Sumit Gupta
Sumit Gupta

Reputation: 44

In the same above snippet, for checking --load flag:

#!/usr/bin/env python3
import argparse
import os
name = None
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-l', '--load', metavar='path', help='Load all JSON 
files recursively in path')

args = parser.parse_args()

print(args.load)

if args.load:
    name = args.load

will assign name to abcxyz, else will be none. If i am able to understand your problem, the above code actually does what you are looking for. The name variable is not really required , just used as an example.

Upvotes: 1

Related Questions