关于Python中argparse.ArgumentParser().add_argument的作用

关于Python中argparse.ArgumentParser().add_argument的作用

在学习tensorflow相关代码时经常会遇到argparse这一模块,本篇博客主要考虑模块中add_argument()以及parse_args()两个函数的作用,下面是试例代码:

import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('input_dir', type=str, help='Directory with unaligned images.')
    parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.')
    parser.add_argument('--image_size', type=int,
                        help='Image size (height, width) in pixels.', default=182)
    parser.add_argument('--margin', type=int,
                        help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)
    parser.add_argument('--random_order',
                        help='Shuffles the order of images to enable alignment using multiple processes.', action='store_true')
    parser.add_argument('--gpu_memory_fraction', type=float,
                        help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)
    parser.parse_args(['hah','aha'])

此时,按照猜想,我们是将hah赋值给input_dir而将aha赋值给output_dir,其余应该是默认值,我们看一下结果,发现,确实是这样,结果如下
在这里插入图片描述
于是我们知道add_argument()是用来指定程序需要接受的命令参数,其中input_dir这一类直接用单引号括起来的表示定位参数而margin这一类前加有–为可选参数,并规定定位参数必选,可选参数可选。
当我们需要为可选参数赋值时,我们修改最后一行代码如下:

parser.parse_args(['hah','aha','--image_size','1','--margin','2','--gpu_memory_fraction','0.0'])

则有输出
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhangshengdong1/article/details/89576564