Python argparse 检查标志是否存在,同时还允许参数 [英] Python argparse check if flag is present while also allowing an argument

查看:29
本文介绍了Python argparse 检查标志是否存在,同时还允许参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查标志 --load 是否存在?

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)

使用 --load 调用脚本输出以下内容:命名空间(load=None)

Calling the script with --load outputs the following: Namespace(load=None)

我不能省略 nargs='?' 并使用 action='store_true',因为我想允许传递参数,例如 <代码>--加载 abcxyz.

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.

添加 action='store_true'nargs='?' 会产生以下错误:

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'

推荐答案

您可以使用 in 运算符来测试是否为(子)命令定义了选项.并且您可以将已定义选项的值与其默认值进行比较,以检查该选项是否在命令行中指定.

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

这篇关于Python argparse 检查标志是否存在,同时还允许参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆