python 命令行传递bool值参数

in note-timknip •  4 years ago 
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
————————————————

虽然type定义为bool,但不管是True还是False, my_bool的值都是True

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',
)

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!