|
5 | 5 | ----------
|
6 | 6 | 问题
|
7 | 7 | ----------
|
8 |
| -You want to write a program that parses options supplied on the command line (found |
9 |
| -in sys.argv). |
| 8 | +你的程序如何能够解析命令行选项(位于sys.argv中) |
10 | 9 |
|
11 | 10 | |
|
12 | 11 |
|
13 | 12 | ----------
|
14 | 13 | 解决方案
|
15 | 14 | ----------
|
16 |
| -The argparse module can be used to parse command-line options. A simple example |
17 |
| -will help to illustrate the essential features: |
18 |
| - |
19 |
| -# search.py |
20 |
| -''' |
21 |
| -Hypothetical command-line tool for searching a collection of |
22 |
| -files for one or more text patterns. |
23 |
| -''' |
24 |
| -import argparse |
25 |
| -parser = argparse.ArgumentParser(description='Search some files') |
26 |
| - |
27 |
| -parser.add_argument(dest='filenames',metavar='filename', nargs='*') |
28 |
| - |
29 |
| -parser.add_argument('-p', '--pat',metavar='pattern', required=True, |
30 |
| - dest='patterns', action='append', |
31 |
| - help='text pattern to search for') |
32 |
| - |
33 |
| -parser.add_argument('-v', dest='verbose', action='store_true', |
34 |
| - help='verbose mode') |
35 |
| - |
36 |
| -parser.add_argument('-o', dest='outfile', action='store', |
37 |
| - help='output file') |
38 |
| - |
39 |
| -parser.add_argument('--speed', dest='speed', action='store', |
40 |
| - choices={'slow','fast'}, default='slow', |
41 |
| - help='search speed') |
42 |
| - |
43 |
| -args = parser.parse_args() |
44 |
| - |
45 |
| -# Output the collected arguments |
46 |
| -print(args.filenames) |
47 |
| -print(args.patterns) |
48 |
| -print(args.verbose) |
49 |
| -print(args.outfile) |
50 |
| -print(args.speed) |
51 |
| - |
52 |
| -This program defines a command-line parser with the following usage: |
53 |
| - |
54 |
| -bash % python3 search.py -h |
55 |
| -usage: search.py [-h] [-p pattern] [-v] [-o OUTFILE] [--speed {slow,fast}] |
56 |
| - [filename [filename ...]] |
57 |
| - |
58 |
| -Search some files |
59 |
| - |
60 |
| -positional arguments: |
61 |
| - filename |
62 |
| - |
63 |
| -optional arguments: |
64 |
| - -h, --help show this help message and exit |
65 |
| - -p pattern, --pat pattern |
66 |
| - text pattern to search for |
67 |
| - -v verbose mode |
68 |
| - -o OUTFILE output file |
69 |
| - --speed {slow,fast} search speed |
70 |
| - |
71 |
| -The following session shows how data shows up in the program. Carefully observe the |
72 |
| -output of the print() statements. |
73 |
| - |
74 |
| -bash % python3 search.py foo.txt bar.txt |
75 |
| -usage: search.py [-h] -p pattern [-v] [-o OUTFILE] [--speed {fast,slow}] |
76 |
| - [filename [filename ...]] |
77 |
| -search.py: error: the following arguments are required: -p/--pat |
78 |
| - |
79 |
| -bash % python3 search.py -v -p spam --pat=eggs foo.txt bar.txt |
80 |
| -filenames = ['foo.txt', 'bar.txt'] |
81 |
| -patterns = ['spam', 'eggs'] |
82 |
| -verbose = True |
83 |
| -outfile = None |
84 |
| -speed = slow |
85 |
| - |
86 |
| -bash % python3 search.py -v -p spam --pat=eggs foo.txt bar.txt -o results |
87 |
| -filenames = ['foo.txt', 'bar.txt'] |
88 |
| -patterns = ['spam', 'eggs'] |
89 |
| -verbose = True |
90 |
| -outfile = results |
91 |
| -speed = slow |
92 |
| - |
93 |
| -bash % python3 search.py -v -p spam --pat=eggs foo.txt bar.txt -o results \ |
94 |
| - --speed=fast |
95 |
| -filenames = ['foo.txt', 'bar.txt'] |
96 |
| -patterns = ['spam', 'eggs'] |
97 |
| -verbose = True |
98 |
| -outfile = results |
99 |
| -speed = fast |
100 |
| - |
101 |
| -Further processing of the options is up to the program. Replace the print() functions |
102 |
| -with something more interesting. |
| 15 | +``argparse`` 模块可被用来解析命令行选项。下面一个简单例子演示了最基本的用法: |
| 16 | + |
| 17 | +.. code-block:: python |
| 18 | +
|
| 19 | + # search.py |
| 20 | + ''' |
| 21 | + Hypothetical command-line tool for searching a collection of |
| 22 | + files for one or more text patterns. |
| 23 | + ''' |
| 24 | + import argparse |
| 25 | + parser = argparse.ArgumentParser(description='Search some files') |
| 26 | +
|
| 27 | + parser.add_argument(dest='filenames',metavar='filename', nargs='*') |
| 28 | +
|
| 29 | + parser.add_argument('-p', '--pat',metavar='pattern', required=True, |
| 30 | + dest='patterns', action='append', |
| 31 | + help='text pattern to search for') |
| 32 | +
|
| 33 | + parser.add_argument('-v', dest='verbose', action='store_true', |
| 34 | + help='verbose mode') |
| 35 | +
|
| 36 | + parser.add_argument('-o', dest='outfile', action='store', |
| 37 | + help='output file') |
| 38 | +
|
| 39 | + parser.add_argument('--speed', dest='speed', action='store', |
| 40 | + choices={'slow','fast'}, default='slow', |
| 41 | + help='search speed') |
| 42 | +
|
| 43 | + args = parser.parse_args() |
| 44 | +
|
| 45 | + # Output the collected arguments |
| 46 | + print(args.filenames) |
| 47 | + print(args.patterns) |
| 48 | + print(args.verbose) |
| 49 | + print(args.outfile) |
| 50 | + print(args.speed) |
| 51 | +
|
| 52 | +该程序定义了一个如下使用的命令行解析器: |
| 53 | + |
| 54 | +.. code-block:: python |
| 55 | +
|
| 56 | + bash % python3 search.py -h |
| 57 | + usage: search.py [-h] [-p pattern] [-v] [-o OUTFILE] [--speed {slow,fast}] |
| 58 | + [filename [filename ...]] |
| 59 | +
|
| 60 | + Search some files |
| 61 | +
|
| 62 | + positional arguments: |
| 63 | + filename |
| 64 | +
|
| 65 | + optional arguments: |
| 66 | + -h, --help show this help message and exit |
| 67 | + -p pattern, --pat pattern |
| 68 | + text pattern to search for |
| 69 | + -v verbose mode |
| 70 | + -o OUTFILE output file |
| 71 | + --speed {slow,fast} search speed |
| 72 | +
|
| 73 | +下面的部分演示了程序中的数据部分。仔细观察print()语句的打印输出。 |
| 74 | +
|
| 75 | +.. code-block:: python |
| 76 | +
|
| 77 | + bash % python3 search.py foo.txt bar.txt |
| 78 | + usage: search.py [-h] -p pattern [-v] [-o OUTFILE] [--speed {fast,slow}] |
| 79 | + [filename [filename ...]] |
| 80 | + search.py: error: the following arguments are required: -p/--pat |
| 81 | +
|
| 82 | + bash % python3 search.py -v -p spam --pat=eggs foo.txt bar.txt |
| 83 | + filenames = ['foo.txt', 'bar.txt'] |
| 84 | + patterns = ['spam', 'eggs'] |
| 85 | + verbose = True |
| 86 | + outfile = None |
| 87 | + speed = slow |
| 88 | +
|
| 89 | + bash % python3 search.py -v -p spam --pat=eggs foo.txt bar.txt -o results |
| 90 | + filenames = ['foo.txt', 'bar.txt'] |
| 91 | + patterns = ['spam', 'eggs'] |
| 92 | + verbose = True |
| 93 | + outfile = results |
| 94 | + speed = slow |
| 95 | +
|
| 96 | + bash % python3 search.py -v -p spam --pat=eggs foo.txt bar.txt -o results \ |
| 97 | + --speed=fast |
| 98 | + filenames = ['foo.txt', 'bar.txt'] |
| 99 | + patterns = ['spam', 'eggs'] |
| 100 | + verbose = True |
| 101 | + outfile = results |
| 102 | + speed = fast |
| 103 | +
|
| 104 | +对于选项值的进一步处理由程序来决定,用你自己的逻辑来替代 ``print()`` 函数。 |
103 | 105 |
|
104 | 106 | |
|
105 | 107 |
|
106 | 108 | ----------
|
107 | 109 | 讨论
|
108 | 110 | ----------
|
109 |
| -The argparse module is one of the largest modules in the standard library, and has a |
110 |
| -huge number of configuration options. This recipe shows an essential subset that can |
111 |
| -be used and extended to get started. |
112 |
| -To parse options, you first create an ArgumentParser instance and add declarations for |
113 |
| -the options you want to support it using the add_argument() method. In each add_ar |
114 |
| -gument() call, the dest argument specifies the name of an attribute where the result of |
115 |
| -parsing will be placed. The metavar argument is used when generating help messages. |
116 |
| -The action argument specifies the processing associated with the argument and is often |
117 |
| -store for storing a value or append for collecting multiple argument values into a list. |
118 |
| -The following argument collects all of the extra command-line arguments into a list. It’s |
119 |
| -being used to make a list of filenames in the example: |
120 |
| - |
121 |
| -parser.add_argument(dest='filenames',metavar='filename', nargs='*') |
122 |
| - |
123 |
| -The following argument sets a Boolean flag depending on whether or not the argument |
124 |
| -was provided: |
125 |
| - |
126 |
| -parser.add_argument('-v', dest='verbose', action='store_true', |
127 |
| - help='verbose mode') |
128 |
| - |
129 |
| -The following argument takes a single value and stores it as a string: |
130 |
| - |
131 |
| -parser.add_argument('-o', dest='outfile', action='store', |
132 |
| - help='output file') |
133 |
| - |
134 |
| -The following argument specification allows an argument to be repeated multiple times |
135 |
| -and all of the values append into a list. The required flag means that the argument must |
136 |
| -be supplied at least once. The use of -p and --pat mean that either argument name is |
137 |
| -acceptable. |
138 |
| - |
139 |
| -parser.add_argument('-p', '--pat',metavar='pattern', required=True, |
140 |
| - dest='patterns', action='append', |
141 |
| - help='text pattern to search for') |
142 |
| - |
143 |
| -Finally, the following argument specification takes a value, but checks it against a set of |
144 |
| -possible choices. |
145 |
| - |
146 |
| -parser.add_argument('--speed', dest='speed', action='store', |
147 |
| - choices={'slow','fast'}, default='slow', |
148 |
| - help='search speed') |
149 |
| - |
150 |
| -Once the options have been given, you simply execute the parser.parse() method. |
151 |
| -This will process the sys.argv value and return an instance with the results. The results |
152 |
| - |
153 |
| -for each argument are placed into an attribute with the name given in the dest parameter |
154 |
| -to add_argument(). |
155 |
| -There are several other approaches for parsing command-line options. For example, |
156 |
| -you might be inclined to manually process sys.argv yourself or use the getopt module |
157 |
| -(which is modeled after a similarly named C library). However, if you take this approach, |
158 |
| -you’ll simply end up replicating much of the code that argparse already provides. You |
159 |
| -may also encounter code that uses the optparse library to parse options. Although |
160 |
| -optparse is very similar to argparse, the latter is more modern and should be preferred |
161 |
| -in new projects. |
| 111 | +``argparse`` 模块是标准库中最大的模块之一,拥有大量的配置选项。 |
| 112 | +本节只是演示了其中最基础的一些特性,帮助你入门。 |
| 113 | +
|
| 114 | +为了解析命令行选项,你首先要创建一个 ``ArgumentParser`` 实例, |
| 115 | +并使用 ``add_argument()`` 方法声明你想要支持的选项。 |
| 116 | +在每个 ``add-argument()`` 调用中,``dest`` 参数指定解析结果被指派给属性的名字。 |
| 117 | +``metavar`` 参数被用来生成帮助信息。``action`` 参数指定跟属性对应的处理逻辑, |
| 118 | +通常的值为 ``store`` ,被用来存储某个值或讲多个参数值收集到一个列表中。 |
| 119 | +下面的参数收集所有剩余的命令行参数到一个列表中。在本例中它被用来构造一个文件名列表: |
| 120 | +
|
| 121 | +.. code-block:: python |
| 122 | +
|
| 123 | + parser.add_argument(dest='filenames',metavar='filename', nargs='*') |
| 124 | +
|
| 125 | +下面的参数根据参数是否存在来设置一个 ``Boolean`` 标志: |
| 126 | +
|
| 127 | +.. code-block:: python |
| 128 | +
|
| 129 | + parser.add_argument('-v', dest='verbose', action='store_true', |
| 130 | + help='verbose mode') |
| 131 | +
|
| 132 | +下面的参数接受一个单独值并将其存储为一个字符串: |
| 133 | +
|
| 134 | +.. code-block:: python |
| 135 | +
|
| 136 | + parser.add_argument('-o', dest='outfile', action='store', |
| 137 | + help='output file') |
| 138 | +
|
| 139 | +下面的参数说明允许某个参数重复出现多次,并将它们追加到一个列表中去。 |
| 140 | +``required`` 标志表示该参数至少要有一个。``-p`` 和 ``--pat`` 表示两个参数名形式都可使用。 |
| 141 | +
|
| 142 | +.. code-block:: python |
| 143 | +
|
| 144 | + parser.add_argument('-p', '--pat',metavar='pattern', required=True, |
| 145 | + dest='patterns', action='append', |
| 146 | + help='text pattern to search for') |
| 147 | +
|
| 148 | +最后,下面的参数说明接受一个值,但是会将其和可能的选择值做比较,以检测其合法性: |
| 149 | +
|
| 150 | +.. code-block:: python |
| 151 | +
|
| 152 | + parser.add_argument('--speed', dest='speed', action='store', |
| 153 | + choices={'slow','fast'}, default='slow', |
| 154 | + help='search speed') |
| 155 | +
|
| 156 | +一旦参数选项被指定,你就可以执行 ``parser.parse()`` 方法了。 |
| 157 | +它会处理 ``sys.argv`` 的值并返回一个结果实例。 |
| 158 | +每个参数值会被设置成该实例中``add_argument()`` 方法的``dest`` 参数指定的属性值。 |
| 159 | +
|
| 160 | +还很多种其他方法解析命令行选项。 |
| 161 | +例如,你可能会手动的处理 ``sys.argv`` 或者使用 ``getopt`` 模块。 |
| 162 | +但是,如果你采用本节的方式,将会减少很多冗余代码,底层细节 ``argparse`` 模块已经帮你处理了。 |
| 163 | +你可能还会碰到使用 ``optparse`` 库解析选项的代码。 |
| 164 | +尽管 ``optparse`` 和 ``argparse`` 很像,但是后者更先进,因此在新的程序中你应该使用它。 |
0 commit comments