1.修改python的传入参数
- 不管什么类型的参数,在 Python 函数中对参数直接使用“=”符号赋值是没用的,直接使用“=”符号赋值并不能改变参数。
- 如果需要让函数修改某些数据,则可以通过把这些数据包装成列表、字典等可变对象,然后把列表、字典等可变对象作为参数传入函数,在函数中通过列表、字典的方法修改它们,这样才能改变这些数据。
2.ArgumentParser对bool类型参数的处理
2.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)
其中store_true意思为触发action时为true,不管是否有default=true默认都为false,即使用时:配置了该参数为true,不配置就是false。
然后我们就可以使用python command --flag或者python command --no-flag来指定flag的值了。注意这里我们使用了parser.add_mutually_exclusive_group来指定这两个参数为互斥参数。这样我们就可以保证二者只有一个能够被指定。python command --flag --no-flag会报错。
2.2add_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'
)
2.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