ArgumentParser对象add_argument()方法
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
参数:
action:指出应该如何处理命令行参数
(支持的操作:’store’ ,’store_const’,’store_true’,’store_false’,’append’,’append_const’,’count’,’help’,’version’)
nargs:将一个动作与不同数目的命令行参数关联在一起(支持的值:N,’?’,’*’,’+’)
default:其默认值为None,指出如果命令行参数没有出现时它们应该是什么值
type:允许任意必要的类型检查并作类型转换
choices:某些命令行参数应该从一个受限的集合中选择
required:如果要使得选项是必需的,可以指定True作为required=关键字参数的值给add_argument()
help:包含参数简短描述的字符串
dest:不懂
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
parser = argparse.ArgumentParser(
description='CNN Training Script')
parser.add_argument('--batch_size', default=8, type=int,
help='Batch size for training')
parser.add_argument('--resume', default=None, type=str,
help='Checkpoint state_dict file to resume training from. If this is "interrupt"'\
', the model will resume training from the interrupt file.')
parser.add_argument('--start_iter', default=-1, type=int,
help='Resume training at this iter. If this is -1, the iteration will be'\
'determined from the file name.')
parser.add_argument('--lr', '--learning_rate', default=None, type=float,
help='Initial learning rate. Leave as None to read this from the config.')
parser.add_argument('--decay', '--weight_decay', default=None, type=float,
help='Weight decay for SGD. Leave as None to read this from the config.')
parser.add_argument('--save_folder', default='weights/',
help='Directory for saving checkpoint models.')
parser.add_argument('--keep_latest', dest='keep_latest', action='store_true',
help='Only keep the latest checkpoint instead of each one.')
parser.add_argument('--log_gpu', dest='log_gpu', action='store_true',
help='Include GPU information in the logs. Nvidia-smi tends to be slow, so set this with caution.')
parser.add_argument('--no_interrupt', dest='interrupt', action='store_false',
help='Don\'t save an interrupt when KeyboardInterrupt is caught.')
parser.add_argument("--resolution", help="resolution:Low, Medium, High",
type=int, default=864, choices=[416,608,864], required=True)
args = parser.parse_args()
def paser_test(a, b, c):
print("this is a test for paser")
print('args.batch_size:',a)
print('args.lr:', b)
print('args.keep_latest:',c)
if __name__ == "__main__":
paser_test(args.batch_size, args.lr, args.keep_latest)
本文深入探讨了Python中argparse模块的ArgumentParser对象及其add_argument方法的使用。详细解释了action、nargs、default、type、choices、required、help、dest等参数的作用,并通过一个CNN训练脚本的例子展示了如何设置和解析命令行参数。
2454

被折叠的 条评论
为什么被折叠?



