您的位置:首页 > 编程语言 > Python开发

Python中argparse模块学习

2017-12-08 22:09 471 查看
今天就结合上一篇博客博客中的一部分代码来记录一下Python中的argparse模块的具体运用

相应的命令行参数为:

第一组:

python tools/train_fg.py –model models/mnist/gcforest/fg-tree500-depth100-3folds.json –log_dir logs/gcforest/mnist/fg –save_outputs

第二组:

python tools/train_cascade.py –model models/mnist/gcforest/fg-tree500-depth100-3folds-ca.json

对于这几个参数在模型训练中的具体解释为

python tools/train_fg.py --model models/mnist/gcforest/fg-tree500-depth100-3folds.json --log_dir logs/gcforest/mnist/fg --save_outputs

This means:
Train a fine grained model for MNIST dataset,
Using the structure defined in models/mnist/gcforest/fg-tree500-depth100-3folds.json
save the log files in logs/gcforest/mnist/fg
The output for the fine grained scanning predictions is saved in train.data_cache.cache_dir

run python tools/train_cascade.py --model models/mnist/gcforest/fg-tree500-depth100-3folds-ca.json

This means:

Train the fine grained scaning results with cascade structure.
The cascade model specification is defined in 'models/mnist/gcforest/fg-tree500-depth100-3folds-ca.json'


以上是我的项目背景中的一部分,下面来正式进入Python argparse模块的讲解:

在Python中非常简单:

1、在导入argparse模块 import argparse

2、新建一个用于命令行参数解析的函数,eg: def parse_args( ):

3、函数中建立解析器: parser = argparse.ArgumentParser()

4、添加要解析的参数:parser.add_argument( )

5、使用parser.parse_args()进行参数解析

# 这个类的设计大致为:
import argparse
def parse_args():
parser=argparse.ArgumentParser()
parser.add_argument('--model', dest='model',type=str,required=True,help="My mood is worry,please chear me up!")
parser.add_argument('--save_outputs','-outputs_save'dest='save_outputs',action='store_true',default=False,help="Save Outputs")
# 添加--save_outputs标签,标签别名可以为-outputs_save
# 这里action的意思是当读取的参数中出现--save_outputs的时候,参数字典的save_outputs建对应的值为True,而help参数用于描述--save_outputs参数的用途或意义。
parser.add_argument('--log_dir',dest='log_dir',type=str,default=None,help="Log file directory")
#注意:--help标签在使用argparse模块时会自动创建,因此一般情况不需要我们主动定义帮助信息
args=parser.parse_arg()
return args


其实步骤中的1、2、3、5都很好理解,下面主要讲解一下步骤4

parser.add_argument()

1) 必需参数 action字段

action参数表示值赋予键的方式,这里用到的是bool类型;eg action=’store_true’,表示当读取的参数中出现了指定参数(键)的时候,参数字典中指定参数(键)的值为True如果是’count’表示将–verbose标签出现的次数作为verbose的值;’append’表示将每次出现的该便签后的值都存入同一个数组再赋值。

以下简单列举参数action的取值:

store:默认action模式,存储值到指定变量。(常用)

store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。

store_true / store_false:布尔开关。可以2个参数对应一个变量。(常用)

append:存储值到列表,该参数可以重复使用。

append_const:存储值到列表,存储值在参数的const部分指定。

version 输出版本信息然后退出。

对于不好理解的取值,请参照以下代码段,一下子就懂了

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store',dest='simple_value',help='Storea simple value')
parser.add_argument('-c', action='store_const',dest='constant_value',const='value-to-store',help='Store a constant value')
parser.add_argument('-t', action='store_true',default=False, dest='boolean_switch', help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=False, dest='boolean_switch', help='Set a switch to false')
parser.add_argument('-a', action='append',dest='collection',default=[],help='Add repeated values to a list')
parser.add_argument('-A', action='append_const',dest='const_collection',const='value-1-to-append',default=[],help='Add different values to list')
parser.add_argument('-B', action='append_const',dest='const_collection',const='value-2-to-append',help='Add different values to list')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
results = parser.parse_args()

# 打印输出参数值
print 'simple_value    = %r' % results.simple_value
print 'constant_value  = %r' % results.constant_value
print 'boolean_switch  = %r' % results.boolean_switch
print 'collection      = %r' % results.collection
print 'const_collection = %r' % results.const_collection

# 对照具体的执行结果来查看参数的用法:

# python argparse_action.py -h
usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t][-f]
[-a COLLECTION] [-A] [-B] [--version]

optional arguments:

-h, --help       show this help message and exit

-s SIMPLE_VALUE  Store a simple value

-c               Store a constant value

-t               Set a switch to true

-f               Set a switch to false

-a COLLECTION    Add repeated values to a list

-A               Add different values to list

-B               Add different values to list

--version        show program's version number and exit

# python argparse_action.py --version

argparse_action.py 1.0

# python argparse_action.py -s value

simple_value     ='value'

constant_value   = None

boolean_switch   = False

collection       = []

const_collection = []

# python argparse_action.py -c

simple_value     = None

constant_value   ='value-to-store'

boolean_switch   = False

collection       = []

const_collection = []

# python argparse_action.py -t

simple_value     = None

constant_value   = None

boolean_switch   = True

collection       = []

const_collection = []

# python argparse_action.py -f

simple_value     = None

constant_value   = None

boolean_switch   = False

collection       = []

const_collection = []

# python argparse_action.py -a one -a two -a three

simple_value     = None

constant_value   = None

boolean_switch   = False

collection       =['one', 'two', 'three']

const_collection = []

# python argparse_action.py -B -A

simple_value     = None

constant_value   = None

boolean_switch   = False

collection       = []
const_collection = ['value-2-to-append', 'value-1-to-append']


具体可以参考网址:https://www.2cto.com/kf/201208/149418.html

2) 必需参数 required字段

这种模式用于确保某些必需的参数有输入。

parser.add_argument(‘–save_outputs’, required=True, type=int)

required标签就是说–verbose参数是必需的,并且类型为int,输入别的类型会报错。

3)位置参数(positional arguments)

位置参数与sys.argv调用比较像,参数没有显式的–xxx或者-xxx标签,因此调用属性也与sys.argv相同。

parser.add_argument(‘filename’) # 输入的第一个参数赋予名为filename的键 仔细阅读这一句话哦

args = parser.parse_args()

print “Read in %s” %(args.filename)

输入python test.py test.txt则会输出Read in test.txt

此外,可以用nargs参数来限定输入的位置参数的个数,默认为1。当然nargs参数也可用于普通带标签的参数。

parser.add_argument(‘num’, nargs=2, type=int)表示脚本可以读入两个整数赋予num键(此时的值为2个整数的数组)。nargs还可以’*’用来表示如果有该位置参数输入的话,之后所有的输入都将作为该位置参数的值;‘+’表示读取至少1个该位置参数。’?’表示该位置参数要么没有,要么就只要一个。(PS:跟正则表达式的符号用途一致。)比如用:

parser.add_argument(‘filename’)

parser.add_argument(‘num’, nargs=’*)

就可以运行python test.py text.txt 1 2

由于没有标签,所以用位置参数的时候需要比较小心。

4)输入类型

之前已经提到了用type参数就可以指定输入的参数类型。而这个type类型还可以表示文件操作的类型从而直接进行文件的读写操作。

parser.add_argument(‘file’, type=argparser.FileType(‘r’)) # 读取文件

args = parser.parse_args()

for line in args.file:

print line.strip()

5)参数默认值

一般情况下会设置一些默认参数从而不需要每次输入某些不需要变动的参数,利用default参数即可实现。

parser.add_argument(‘filename’, default=’text.txt’)

这个时候至直接运行python text.py就能得到Read in text.txt而不需要输入文件名了。

6)候选参数选择

表示该参数能接受的值只能来自某几个值候选值中,除此以外会报错,用choices参数即可。比如:

parser.add_argument(‘filename’, choices=[‘test1.txt’, ‘text2.txt’])

参考网址:https://www.cnblogs.com/arkenstone/p/6250782.html

今天就记录到这里了,虽然身体有点不舒服,但是每天学一点总是好的,每天爱自己多一点!!晚安
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: