转载自:
https://blog.csdn.net/yaokai_assultmaster/article/details/77928629
这位大佬的博客已经写得hin详细了
指定一个boolean类型的argument
虽然argparse用起来非常方便,然而遗憾的是其在处理boolean类型的参数的时候并不能自动转换参数类型。也就是说,对于如下这种参数:
parser = argparse.ArgumentParser()
parser.add_argument(
'--bool-arg',
help='this is a True or False we want',
dest='bool_arg',
type=bool,
)
args = parser.parse_args()
my_bool = args.bool_arg
虽然我们指定了其类型为bool,但无论我们在命令行中给这个参数传入什么值(如True,False等),my_bool的值总是为True。
那么我们究竟应该如何从命令行中接收一个能够返回boolean类型值的参数呢?
有如下三种方法:
1.分别使用不同的参数标识我们需要的flag
flag_parser = parser.add_mutually_exclusive_group(required=False)
flag_parser.add_argument('--flag', dest='flag', action='store_true')
flag_parser.add_argument('--no-flag', dest='flag', action='store_false')
parser.set_defaults(flag=True)
然后我们就可以使用python command --flag
或者python command --no-flag
来指定flag的值了。注意这里我们使用了parser.add_mutually_exclusive_group
来指定这两个参数为互斥参数。这样我们就可以保证二者只有一个能够被指定。python command --flag --no-flag
会报错。
2.定义一个函数作为传入type的callable帮我们进行类型转换
add_argument
所接收的一个callable类型的type参数可以帮我们对收到的原始参数进行处理。所以我们可以定义一个函数作为type帮我们进行预处理。比如如下例子:
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Unsupported value encountered.')
parser.add_argument(
'--flag',
type=str2bool,
nargs='?',
const=True,
help='Turn on or turn off flag'
)
当我们使用上面这个例子的时候,程序可以这样调用:
python command --flag # 使用const中指定的值作为参数值
python command --flag 0
3.使用ast.literal_eval作为type
下面是ast.literal_eval的文档:
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
可以得知,ast.literal_eval
可以从字符串中读取Python的string, numbers, tuples, lists, dicts, booleans and None
类型的对象。所以我们只需指定当前argument的type为ast.literal_eval
,就可以得到boolean类型的值了。但这种方法的问题在于,只有当参数输入为’False’时读取的值才为False,否则为True。如下面的例子所示:
parser.add_argument(
'--flag',
help='True or False flag, input should be either "True" or "False".',
type=ast.literal_eval,
dest='flag',
)
调用方法为:
python command --flag True
python command --flag False