一、argparse模块用法
1、argparse是一个python模块,用途是:命令行选项、参数和子命令的解释。
2、argparse库下载:pip install argparse
3、使用步骤:
导入argparse模块,并创建解释器
添加所需参数
解析参数
二、代码
cpp
import argparse
def add_common_arguments(parser):
"""Add common arguments for training and inference."""
parser.add_argument('--save_best_weights',
default='model_data/best.pth',
help="save best weights name.")
parser.add_argument('--phi', type=str, default='s')
parser.add_argument('--num_classes', type=int, default=10)
def get_parser_for_training():
"""Return argument parser for training."""
# -------------------------------------------#
# Step 1. 构造解析器 argparse.ArgumentParser()
# -------------------------------------------#
parser = argparse.ArgumentParser("Training args")
# -------------------------------------------#
# Step 2. 添加参数 .add_argument()
# -------------------------------------------#
parser.add_argument('--train_path',default='/data/train',help="The location of dataset.")
parser.add_argument('--sync_bn', type=bool,default=False,help='use SyncBatchNorm, only available in DDP mode')
parser.add_argument('--Cuda', type=bool,default=True)
parser.add_argument('--fp16', type=bool,default=False)
parser.add_argument('--num_workers', type=int, default=8,help="Number of workers for data loading.")
parser.add_argument('--Total_epoch', type=int, default=300,help='Total Epoch')
parser.add_argument('--Batch_size', type=int, default=64,help='Batch_size')
# -------------------------------------------#
# Step 2. 添加参数 .add_argument()
# -------------------------------------------#
add_common_arguments(parser)
return parser
if __name__=='__main__':
# -------------------------------------------#
# Step 3. 解析参数 .parse_args()
# -------------------------------------------#
train_parser = get_parser_for_training()
train_args = train_parser.parse_args()
print(train_args)
# -------------------------------------------#
# training args
# -------------------------------------------#
print("training data path:",train_args.train_path)
print("training batch size:",train_args.Batch_size)
print("Cuda:",train_args.Cuda)
# -------------------------------------------#
# common args
# -------------------------------------------#
print("num classes:",train_args.num_classes)
print("phi:",train_args.phi)
print("save model path:",train_args.save_best_weights)
运行结果
用命令行查看parser的所有参数选项
用命令行修改parser的特定参数