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

大城市里の小女人 提交于 2020-01-24 19:56:46

问题


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'

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/45140656/python-argparse-check-if-flag-is-present-while-also-allowing-an-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!