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

python学习之 argparse

2016-09-24 15:11 399 查看
官方文档:https://docs.python.org/2/library/argparse.html本文主要内容来自官方文档(即上面的链接)。本文主要说明了一件事:argparse是用来干什么的。

argparse干了什么?

对于propositional argument(关于什么是propositional argument,请阅读官方文档)看两个例子

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.foo
import argparseparser = argparse.ArgumentParser()parser.add_argument("square", help="display a square of a given number")args = parser.parse_args()print args.square**2
这两个例子说明,argparse对于propositional argument其实是把命令行参数中合适的参数赋值给了我们指定的参数,比如args.square得到了我们指定的int,而上面的echo得到了我们给定的字符串

Optional arguments

So far we, have been playing with positional arguments. Let us have a look on how to add optional ones:
import argparseparser = argparse.ArgumentParser()parser.add_argument("--verbosity", help="increase output verbosity")args = parser.parse_args()if args.verbosity:    print "verbosity turned on"print args.verbosity
说明optional argument 和 propositional argument的意义是一样的,只是optional arguemnt在参数后面的值会被赋予给args.verbosity

关于action关键字:

import argparseparser = argparse.ArgumentParser()parser.add_argument("--verbose", help="increase output verbosity",action="store_true")args = parser.parse_args()if args.verbose:print "verbosity turned on"
 the value
"store_true"
.This means that, if the option is specified, assign the value 
True
 to 
args.verbose
.Not specifying it implies 
False
.

   Short options

If you are familiar with command line usage, you will notice that I haven’t yet touched on the topic of short versions of the options. It’s quite simple:
import argparseparser = argparse.ArgumentParser()parser.add_argument("-v", "--verbose", help="increase output verbosity",action="store_true")args = parser.parse_args()if args.verbose:print "verbosity turned on"
And here goes:
$ python prog.py -vverbosity turned on$ python prog.py --helpusage: prog.py [-h] [-v]optional arguments:-h, --help     show this help message and exit-v, --verbose  increase output verbosity
Note that the new ability is also reflected in the help text.

   Combining Positional and Optional arguments

Our program keeps growing in complexity:
import argparseparser = argparse.ArgumentParser()parser.add_argument("square", type=int,help="display a square of a given number")parser.add_argument("-v", "--verbose", action="store_true",help="increase output verbosity")args = parser.parse_args()answer = args.square**2if args.verbose:print "the square of {} equals {}".format(args.square, answer)else:print answer
And now the output:
$ python prog.pyusage: prog.py [-h] [-v] squareprog.py: error: the following arguments are required: square$ python prog.py 416$ python prog.py 4 --verbosethe square of 4 equals 16$ python prog.py --verbose 4the square of 4 equals 16
We’ve brought back a positional argument, hence the complaint.Note that the order does not matter.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: