Skip to content

Commit 6f76271

Browse files
committed
add argparse
1 parent 5e1682b commit 6f76271

1 file changed

Lines changed: 183 additions & 0 deletions

File tree

Standard-Modules/argparse.md

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
# argparse
2+
3+
argparse 是 Python 内置的一个用于命令项选项与参数解析的模块,通过在程序中定义好我们需要的参数,argparse 将会从 sys.argv 中解析出这些参数,并自动生成帮助和使用信息。当然,Python 也有第三方的库可用于命令行解析,而且功能也更加强大,比如 [docopt](http://docopt.org/)[Click](http://click.pocoo.org/5/)
4+
5+
# argparse 使用
6+
7+
## 简单示例
8+
9+
我们先来看一个简单示例。主要有三个步骤:
10+
11+
- 创建 ArgumentParser() 对象
12+
- 调用 add_argument() 方法添加参数
13+
- 使用 parse_args() 解析添加的参数
14+
15+
```python
16+
# -*- coding: utf-8 -*-
17+
18+
import argparse
19+
20+
parser = argparse.ArgumentParser()
21+
parser.add_argument('integer', type=int, help='display an integer')
22+
args = parser.parse_args()
23+
24+
print args.integer
25+
```
26+
27+
将上面的代码保存为文件 `argparse_usage.py`,在终端运行,结果如下:
28+
29+
```
30+
$ python argparse_usage.py
31+
usage: argparse_usage.py [-h] integer
32+
argparse_usage.py: error: too few arguments
33+
34+
$ python argparse_usage.py abcd
35+
usage: argparse_usage.py [-h] integer
36+
argparse_usage.py: error: argument integer: invalid int value: 'abcd'
37+
38+
$ python argparse_usage.py -h
39+
usage: argparse_usage.py [-h] integer
40+
41+
positional arguments:
42+
integer display an integer
43+
44+
optional arguments:
45+
-h, --help show this help message and exit
46+
47+
$ python argparse_usage.py 10
48+
10
49+
```
50+
51+
## 定位参数
52+
53+
上面的示例,其实就展示了定位参数的使用,我们再来看一个例子 - 计算一个数的平方:
54+
55+
```py
56+
# -*- coding: utf-8 -*-
57+
58+
import argparse
59+
60+
parser = argparse.ArgumentParser()
61+
parser.add_argument("square", help="display a square of a given number", type=int)
62+
args = parser.parse_args()
63+
print args.square**2
64+
```
65+
66+
将上面的代码保存为文件 `argparse_usage.py`,在终端运行,结果如下:
67+
68+
```
69+
$ python argparse_usage.py 9
70+
81
71+
```
72+
73+
## 可选参数
74+
75+
现在看下可选参数的用法,所谓可选参数,也就是命令行参数是可选的,废话少说,看下面例子:
76+
77+
```
78+
# -*- coding: utf-8 -*-
79+
80+
import argparse
81+
82+
parser = argparse.ArgumentParser()
83+
84+
parser.add_argument("--square", help="display a square of a given number", type=int)
85+
parser.add_argument("--cubic", help="display a cubic of a given number", type=int)
86+
87+
args = parser.parse_args()
88+
89+
if args.square:
90+
print args.square**2
91+
92+
if args.cubic:
93+
print args.cubic**3
94+
```
95+
96+
将上面的代码保存为文件 `argparse_usage.py`,在终端运行,结果如下:
97+
98+
```
99+
$ python argparse_usage.py --h
100+
usage: argparse_usage.py [-h] [--square SQUARE] [--cubic CUBIC]
101+
102+
optional arguments:
103+
-h, --help show this help message and exit
104+
--square SQUARE display a square of a given number
105+
--cubic CUBIC display a cubic of a given number
106+
107+
$ python argparse_usage.py --square 8
108+
64
109+
110+
$ python argparse_usage.py --cubic 8
111+
512
112+
113+
$ python argparse_usage.py 8
114+
usage: argparse_usage.py [-h] [--square SQUARE] [--cubic CUBIC]
115+
argparse_usage.py: error: unrecognized arguments: 8
116+
117+
$ python argparse_usage.py # 没有输出
118+
```
119+
120+
## 混合使用
121+
122+
定位参数和选项参数可以混合使用,看下面一个例子,给一个整数序列,输出它们的和或最大值(默认):
123+
124+
```py
125+
import argparse
126+
127+
parser = argparse.ArgumentParser(description='Process some integers.')
128+
parser.add_argument('integers', metavar='N', type=int, nargs='+',
129+
help='an integer for the accumulator')
130+
parser.add_argument('--sum', dest='accumulate', action='store_const',
131+
const=sum, default=max,
132+
help='sum the integers (default: find the max)')
133+
134+
args = parser.parse_args()
135+
print args.accumulate(args.integers)
136+
```
137+
138+
结果:
139+
140+
```py
141+
$ python argparse_usage.py
142+
usage: argparse_usage.py [-h] [--sum] N [N ...]
143+
argparse_usage.py: error: too few arguments
144+
$ python argparse_usage.py 1 2 3 4
145+
4
146+
$ python argparse_usage.py 1 2 3 4 --sum
147+
10
148+
```
149+
150+
## add_argument() 方法
151+
152+
add_argument() 方法定义如何解析命令行参数:
153+
154+
```
155+
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
156+
```
157+
158+
每个参数解释如下:
159+
160+
- name or flags - 选项字符串的名字或者列表,例如 foo 或者 -f, --foo。
161+
- action - 命令行遇到参数时的动作,默认值是 store。
162+
- store_const,表示赋值为const;
163+
- append,将遇到的值存储成列表,也就是如果参数重复则会保存多个值;
164+
- append_const,将参数规范中定义的一个值保存到一个列表;
165+
- count,存储遇到的次数;此外,也可以继承 argparse.Action 自定义参数解析;
166+
- nargs - 应该读取的命令行参数个数,可以是具体的数字,或者是?号,当不指定值时对于 Positional argument 使用 default,对于 Optional argument 使用 const;或者是 * 号,表示 0 或多个参数;或者是 + 号表示 1 或多个参数。
167+
- const - action 和 nargs 所需要的常量值。
168+
- default - 不指定参数时的默认值。
169+
- type - 命令行参数应该被转换成的类型。
170+
- choices - 参数可允许的值的一个容器。
171+
- required - 可选参数是否可以省略 (仅针对可选参数)。
172+
- help - 参数的帮助信息,当指定为 `argparse.SUPPRESS` 时表示不显示该参数的帮助信息.
173+
- metavar - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称.
174+
- dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线.
175+
176+
# 参考资料
177+
178+
- [Argparse Tutorial — Python 2.7.12 documentation](https://docs.python.org/2/howto/argparse.html)
179+
- [Argparse – Command line option and argument parsing](https://pymotw.com/2/argparse/)
180+
- [Argparse — Parser for command-line options, arguments and sub-commands](http://python.usyiyi.cn/python_278/library/argparse.html)
181+
- [Python 中的命令行解析工具介绍](http://lingxiankong.github.io/blog/2014/01/14/command-line-parser/)
182+
183+

0 commit comments

Comments
 (0)