Python 有两个内建的模块用于处理命令行参数:
  一个是 getopt只能简单处理 命令行参数;
另一个是 optparse,它功能强大,而且易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。会自动帮你负责-h帮助选项。
更高级的可以使用argparse这个模块,argparse从python2.7开始被加入标准库. 后续版本都不在维护 optparse 了.

Python command line parsing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
https://code.google.com/archive/p/argparse/

Python command line parsing

The argparse module is now part of the Python standard library!
All new development on argparse will continue in the Python repository. Get Python 2.7 or 3.2 for the latest argparse updates!

Additionally, there is an effort to maintain an argparse package here: * it is based on the python 2.7 stdlib code, backported to older python versions * provides argparse for everybody who still needs to support python < 2.7 * provides argparse >= 1.2 under Python license to fix license compatibility issues (e.g. Apache License 2.0 is considered incompatible to GPL v2) * fix other issues as they come up without forcing people to use python 2.7

argparse: Python command line parser
The argparse module provides an easy, declarative interface for creating command line tools, which knows how to:

parse the arguments and flags from sys.argv
convert arg strings into objects for your program
format and print informative help messages
and much more...
The argparse module improves on the standard library optparse module in a number of ways including:

handling positional arguments
supporting sub-commands
allowing alternative option prefixes like + and /
handling zero-or-more and one-or-more style arguments
producing more informative usage messages
providing a much simpler interface for custom types and actions
See the argparse documentation in the Python standard library.

optparse 模块介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
https://pymotw.com/2/optparse/
下面是一个简单的例子.
import optparse

parser = optparse.OptionParser()

parser.add_option('-q', action='store_const', const='query', dest='mode', help='Query')
parser.add_option('-i', action='store_const', const='install', dest='mode', help='Install')

query_opts = optparse.OptionGroup(parser, 'Query Options', 'These options control the query mode.',)
query_opts.add_option('-l', action='store_const', const='list', dest='query_mode', help='List contents')
query_opts.add_option('-f', action='store_const', const='file', dest='query_mode', help='Show owner of file')
query_opts.add_option('-a', action='store_const', const='all', dest='query_mode', help='Show all packages')
parser.add_option_group(query_opts)

install_opts = optparse.OptionGroup(parser, 'Installation Options','These options control installation.',)
install_opts.add_option('--hash', action='store_true', default=False, help='Show hash marks as progress indication')
install_opts.add_option('--force', dest='install_force', action='store_true', default=False, help='Install, regardless of depdencies or existing version')
parser.add_option_group(install_opts)

print parser.parse_args()


$ python optparse_groups.py -h

Usage: optparse_groups.py [options]

Options:
-h, --help show this help message and exit
-q Query
-i Install

Query Options:
These options control the query mode.

-l List contents
-f Show owner of file
-a Show all packages

Installation Options:
These options control installation.

--hash Show hash marks as progress indication
--force Install, regardless of depdencies or existing version




argparse 模块介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
https://pymotw.com/2/argparse/index.html

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-s', action='store', dest='simple_value', help='Store a 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')

group = parser.add_argument_group('authentication')

group.add_argument('--user', action="store")
group.add_argument('--password', action="store")

results = parser.parse_args()



奇技淫巧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
下面再说个 optparse 的技巧.Extending optparse
Since the two major controlling factors in how optparse interprets command-line options are the action and type of each option, the most likely direction of extension is to add new actions and new types. 也就是自定义 add_option() 方法中的 action 和 type.
下面举个例子:
from optparse import Option, OptionValueError, OptionParser
from copy import copy
from datetime import datetime

# function to check/convert option value to datetime object
def valid_date(option, opt, value):
try:
return datetime.strptime(value,'%Y%m%d')
except ValueError:
raise OptionValueError( 'option %s: invalid date format: %r' % (opt, value))

# extend Option class with date type
class MyOption(Option):
TYPES = Option.TYPES + ('date',) # 这里是元组相加,会得到一个新的元组, 不需要copy了。
TYPE_CHECKER = copy(Option.TYPE_CHECKER) # 这里字典类型的 需要copy 一份,再往里面放新的值, 不然会影响 原生的。
TYPE_CHECKER['date'] = valid_date

# parse options
parser = OptionParser(option_class=MyOption)
parser.add_option( '-e', '--end', type='date' , help='end date - format YYYYMMDD')
(opts, args) = parser.parse_args()

# do something meaningful
print opts.end

这个例子是想 自定义一个 日期 date的 type, 命令行按照特定的格式输入日期, 到python中会转换成对应的 datetime 类型,而不是字符串类型了.
这个功能如果要argparse来实现会很简单的.add_argument() 方法中有个type参数, 可以支持传入一个方法, 然后命令行参数会经过这个方法预处理处理的.

def str_strip(v):
return v.strip() if v else v

def str_bool(v):
if v.lower() in ('yes', 'true', 'y'):
return True
elif v.lower() in ('no', 'false', 'n'):
return False
else:
raise argparse.ArgumentTypeError('Unsupported value encountered.')

parser = argparse.ArgumentParser()
parser.add_argument('--str', dest='str', required=True, type=str_strip) # 这里--str 后面的参数会经过 str_strip(v)方法处理一下,也就是去除前后空格.
parser.add_argument('--is', dest='is', required=True, type=str_bool) # --is 后面的参数 会经过 str_bool(v)处理,一般jenkins上的job配置成boolean类型的参数
那么这个参数值会是 字符串的 true 或者 false, 和python中的True,False 不对应的, 这里经过 str_bool(v)处理就会把 字符串的true转换成python的True, 字符串的false 转换为python的False了。不需要你在python 这样在判断了 v = True if v == "true" else False