使用Python中的argparse从命令行接收boolean类型的参数

Python程序从命令行读取参数

很多时候,为了使我们所写的程序更加灵活,我们会给这个程序加上在命令行中调用时可以指定参数的功能。Python中argparse就是一个方便使用的读取命令行参数的库。使用argparse读取在命令行调用程序时指定的参数的示例代码如下:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument(
        'positional_argument',
        help='this is a positional argument',
    )
    parser.add_argument(
        '--arg1',
        help='the first argument',
        type=int,
        dest='arg1',
        default=1,
    )
    parser.add_argument(
        '--arg2',
        help='the second argument',
        type=str,
        dest='arg2',
    )

    args = parser.parse_args()
    pos_argument = args.positional_argument
    arg1 = args.arg1
    arg2 = args.arg2

接下来在调用这个程序的时候,我们只需要使用如下命令即可将相应的positional argumentkeyword argument传入程序中:

python out_program.py positional_argument --arg1 0 --arg2 argument

如果我们想要指定一个boolean类型的argument作为某种flag使用呢?

虽然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类型值的参数呢?

有如下三种方法:

分别使用不同的参数标识我们需要的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会报错。

定义一个函数作为传入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

使用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