argparse 是python自带的命令行参数解析包,可以用来方便地读取命令行参数。
以mmdetection3d的train.py脚本为例:
import argparse
def parse_args():
# 1.创建命令行解释器,description可写可不写,在出错时会打印
parser = argparse.ArgumentParser(description='Train a detector')
# 2. 添加需要的参数
"""
参数解释:
· 单引号内无小横杠,则要求必须输入该参数,如'config',且不需要指定参数名称,指定会报错
· -xx为短选项,目的是简化参数
· --xxx为完整的参数名
· choices=[]代表输入参数只能从中选取
· type代表输入参数的类型,默认为字符串
· default代表如果不输入,默认使用该值
· help代表参数的帮助信息
· action代表命令行遇到flags参数时的动作。有两个常见的动作,store_true:设定flag参数为
true;store_false:设定flag参数为False。注意:如果直接运行程序,默认不读取该变量,要使用
必须要进行传参,例如:python train.py --work-dir
· nargs: 应该读取的命令行参数个数,可以是具体的数字,或者是?号,当不指定值时对于 Positional
argument 使用 default,对于 Optional argument 使用 const;或者是 * 号,表示 0 或多个参
数;或者是 + 号表示 1 或多个参数。
"""
parser.add_argument('config', help='train config file path')
parser.add_argument('--work-dir', help='the dir to save logs and models')
parser.add_argument(
'--resume-from', help='the checkpoint file to resume from')
parser.add_argument(
'--auto-resume',
action='store_true',
help='resume from the latest checkpoint automatically')
parser.add_argument(
'--no-validate',
action='store_true',
help='whether not to evaluate the checkpoint during training')
group_gpus = parser.add_mutually_exclusive_group()
group_gpus.add_argument(
'--gpus',
type=int,
help='(Deprecated, please use --gpu-id) number of gpus to use '
'(only applicable to non-distributed training)')
group_gpus.add_argument(
'--gpu-ids',
type=int,
nargs='+',
help='(Deprecated, please use --gpu-id) ids of gpus to use '
'(only applicable to non-distributed training)')
group_gpus.add_argument(
'--gpu-id',
type=int,
default=0,
help='number of gpus to use '
'(only applicable to non-distributed training)')
parser.add_argument('--seed', type=int, default=0, help='random seed')
parser.add_argument(
'--diff-seed',
action='store_true',
help='Whether or not set different seeds for different ranks')
parser.add_argument(
'--deterministic',
action='store_true',
help='whether to set deterministic options for CUDNN backend.')
parser.add_argument(
'--options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file (deprecate), '
'change to --cfg-options instead.')
parser.add_argument(
'--cfg-options',
nargs='+',
action=DictAction,
help='override some settings in the used config, the key-value pair '
'in xxx=yyy format will be merged into config file. If the value to '
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
'Note that the quotation marks are necessary and that no white space '
'is allowed.')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument(
'--autoscale-lr',
action='store_true',
help='automatically scale lr with the number of gpus')
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
if args.options and args.cfg_options:
raise ValueError(
'--options and --cfg-options cannot be both specified, '
'--options is deprecated in favor of --cfg-options')
if args.options:
warnings.warn('--options is deprecated in favor of --cfg-options')
args.cfg_options = args.options
return args
def main():
# 从命令行中结构化解析参数
args = parse_args()
if __name__ == '__main__':
main()
另外,在pycharm中,对于命令行参数的读取: