Argparse Tutorial
authorTshepang Lekhonkhobe
| This tutorial is intended to be a gentle introduction to argparse, the recommended command-line parsing module in the Python standard library. | 本教程旨在温和地介绍 argparse,它是 Python 标准库中推荐的命令行解析模块。 |
|---|---|
| :::info |
Note
There are two other modules that fulfill the same task, namely getopt (an equivalent for getopt() from the C language) and the deprecated optparse. Note also that argparse is based on optparse, and therefore very similar in terms of usage.
:::
| 注意
还有两个模块可以完成同样的任务,即 getopt (相当于 C 语言中的 getopt() ) 和已被废弃的 optparse。还要注意的是,argparse 是基于 optparse 的,因此在用法上非常相似。 |
Concepts
| Let’s show the sort of functionality that we are going to explore in this introductory tutorial by making use of the ls command: | 让我们通过利用ls命令来展示我们将在这个入门教程中探索的那种功能。 |
|---|---|
| ```shell |
$ ls cpython devguide prog.py pypy rm-unused-function.patch $ ls pypy ctypes_configure demo dotviewer include lib_pypy lib-python … $ ls -l total 20 drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy -rw-r—r— 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch $ ls —help Usage: ls [OPTION]… [FILE]… List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor —sort is specified. …
| || A few concepts we can learn from the four commands:<br />- The **ls** command is useful when run without any options at all. It defaults to displaying the contents of the current directory.<br />- If we want beyond what it provides by default, we tell it a bit more. In this case, we want it to display a different directory, pypy. What we did is specify what is known as a positional argument. It’s named so because the program should know what to do with the value, solely based on where it appears on the command line. This concept is more relevant to a command like **cp**, whose most basic usage is cp SRC DEST. The first position is _what you want copied,_ and the second position is _where you want it copied to_.<br />- Now, say we want to change behaviour of the program. In our example, we display more info for each file instead of just showing the file names. The -l in that case is known as an optional argument.<br />- That’s a snippet of the help text. It’s very useful in that you can come across a program you have never used before, and can figure out how it works simply by reading its help text.<br /> | 我们可以从这四个命令中学到一些概念。<br /><br />- ls命令在没有任何选项的情况下运行是很有用的。它默认显示的是当前目录的内容。<br /><br /><br />- 如果我们想要超出它默认提供的内容,我们可以告诉它更多。在这个例子中,我们想让它显示一个不同的目录,即pypy。我们所做的是指定一个被称为位置参数的东西。之所以这样命名,是因为程序应该知道如何处理这个值,完全基于它在命令行中出现的位置。这个概念与cp这样的命令更相关,它的最基本用法是cp SRC DEST。第一个位置是你想复制的东西,第二个位置是你想复制到哪里。<br /><br /><br /><br /><br />- 现在,假设我们想改变程序的行为。在我们的例子中,我们为每个文件显示更多信息,而不是只显示文件名。在这种情况下,-l被称为一个可选参数。<br /><br /><br />- 这就是帮助文本的一个片段。它非常有用,你可以遇到一个你从未使用过的程序,只需阅读它的帮助文本就可以知道它是如何工作的。<br /> |<a name="QoHbc"></a>## The basics| Let us start with a very simple example which does (almost) nothing: | 我们从一个(几乎)尚未处理任何命令行参数的简单例子开始: || --- | --- || ```pythonimport argparseparser = argparse.ArgumentParser()parser.parse_args()
| | | Following is a result of running the code: | 以下是运行代码的结果: | | ```shell $ python3 prog.py $ python3 prog.py —help usage: prog.py [-h]
options: -h, —help show this help message and exit $ python3 prog.py —verbose usage: prog.py [-h] prog.py: error: unrecognized arguments: —verbose $ python3 prog.py foo usage: prog.py [-h] prog.py: error: unrecognized arguments: foo
| || Here is what is happening:<br />- Running the script without any options results in nothing displayed to stdout. Not so useful.<br />- The second one starts to display the usefulness of the [argparse](https://docs.python.org/3/library/argparse.html#module-argparse) module. We have done almost nothing, but already we get a nice help message.<br />- The --help option, which can also be shortened to -h, is the only option we get for free (i.e. no need to specify it). Specifying anything else results in an error. But even then, we do get a useful usage message, also for free.<br /> | 现在的情况是这样的。<br />- 在没有任何选项的情况下运行该脚本,结果是没有任何东西显示在stdout中。这不是很有用。<br /><br /><br />- 第二个例子开始显示argparse模块的有用性。我们几乎什么都没做,但我们已经得到了一个很好的帮助信息。<br /><br /><br />- --help选项,也可以简称为-h,是我们唯一免费得到的选项(也就是说,不需要指定)。指定其他任何东西都会导致一个错误。但即使如此,我们也能得到一个有用的使用信息,也是免费的。<br /> |<a name="aQY4X"></a>## Introducing Positional arguments【位置参数:必传】| An example: | 如下案例: || --- | --- || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("echo")args = parser.parse_args()print(args.echo)
| | | And running the code: | 运行代码 | | ```shell $ python3 prog.py usage: prog.py [-h] echo prog.py: error: the following arguments are required: echo $ python3 prog.py —help usage: prog.py [-h] echo
positional arguments: echo
options: -h, —help show this help message and exit $ python3 prog.py foo foo
| || Here is what’s happening:<br />- We’ve added the `add_argument()` method, which is what we use to specify which command-line options the program is willing to accept. In this case, I’ve named it echo so that it’s in line with its function.<br />- Calling our program now requires us to specify an option.<br />- The `parse_args()` method actually returns some data from the options specified, in this case, echo.<br />- The variable is some form of ‘magic’ that [argparse](https://docs.python.org/3/library/argparse.html#module-argparse) performs for free (i.e. no need to specify which variable that value is stored in). You will also notice that its name matches the string argument given to the method, echo.<br /> | 这里是正在发生的事情。<br />- 我们添加了add_argument()方法,我们用它来指定程序愿意接受哪些命令行选项。在这个例子中,我把它命名为echo,这样就和它的功能一致了。<br /><br /><br />- 现在调用我们的程序需要我们指定一个选项。<br /><br /><br />- parse_args()方法实际上是从指定的选项中返回一些数据,在本例中是echo。<br /><br /><br />- 这个变量是argparse免费执行的某种形式的 "魔法"(即不需要指定该值存储在哪个变量中)。你还会注意到,它的名字与方法所给的字符串参数相匹配,即echo。<br /> || Note however that, although the help display looks nice and all, it currently is not as helpful as it can be. For example we see that we got echo as a positional argument, but we don’t know what it does, other than by guessing or by reading the source code. So, let’s make it a bit more useful: | 然而,请注意,尽管帮助显示看起来很好,但目前它并不像它所能提供的那样有用。<br />例如,我们看到我们得到了echo作为一个位置参数,但我们不知道它的作用,只能通过猜测或阅读源代码来了解。<br />所以,让我们让它变得更有用一些。 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("echo", help="echo the string you use here")args = parser.parse_args()print(args.echo)
| | | And we get: | | | ```shell $ python3 prog.py -h usage: prog.py [-h] echo
positional arguments: echo echo the string you use here
options: -h, —help show this help message and exit
| || Now, how about doing something even more useful: | 现在,做一些更有用的事情怎么样: || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("square", help="display a square of a given number")args = parser.parse_args()print(args.square**2) # 拿到对象的属性(其类型默认str)
| |
| Following is a result of running the code: | 运行结果 |
| ```shell
$ python3 prog.py 4
Traceback (most recent call last):
File “prog.py”, line 5, in
| || That didn’t go so well. That’s because [argparse](https://docs.python.org/3/library/argparse.html#module-argparse) treats the options we give it as strings, unless we tell it otherwise. So, let’s tell [argparse](https://docs.python.org/3/library/argparse.html#module-argparse) to treat that input as an integer: | 这并不顺利。这是因为argparse把我们给它的选项当成了字符串,除非我们告诉它。所以,让我们告诉argparse把这个输入当作一个整数。 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("square", help="display a square of a given number", type=int)args = parser.parse_args()print(args.square**2)
| | | Following is a result of running the code: | 运行结果 | | ```python $ python3 prog.py 4 16 $ python3 prog.py four usage: prog.py [-h] square prog.py: error: argument square: invalid int value: ‘four’
| || That went well. The program now even helpfully quits on bad illegal input before proceeding. | 进展顺利。该程序现在甚至可以在继续之前退出错误的非法输入。 |<a name="r88Tv"></a>## Introducing Optional arguments【可选选项,不要求】| So far we have been playing with positional arguments. Let us have a look on how to add optional ones: | 到目前为止,我们一直在使用位置参数。让我们来看看如何添加可选参数。 || --- | --- || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("--verbosity", help="increase output verbosity")args = parser.parse_args()if args.verbosity:print("verbosity turned on")
| | | And the output: | 运行结果 | | ```shell $ python3 prog.py —verbosity 1 verbosity turned on $ python3 prog.py $ python3 prog.py —help usage: prog.py [-h] [—verbosity VERBOSITY]
options: -h, —help show this help message and exit —verbosity VERBOSITY increase output verbosity $ python3 prog.py —verbosity usage: prog.py [-h] [—verbosity VERBOSITY] prog.py: error: argument —verbosity: expected one argument
| || Here is what is happening:<br />- The program is written so as to display something when --verbosity is specified and display nothing when not.<br />- To show that the option is actually optional, there is no error when running the program without it. Note that by default, if an optional argument isn’t used, the relevant variable, in this case `args.verbosity`, is given None as a value, which is the reason it fails the truth test of the [if](https://docs.python.org/3/reference/compound_stmts.html#if) statement.<br />- The help message is a bit different.<br />- When using the --verbosity option, one must also specify some value, any value.<br /> | 以下是正在发生的情况。<br />- 程序的编写是为了在指定--verbosity时显示一些东西,而在不指定时什么也不显示。<br /><br /><br />- 为了表明该选项实际上是可选的,在没有该选项的情况下运行程序时不会出现错误。注意,在默认情况下,如果没有使用一个可选参数,相关的变量,在本例中是args.verbosity,会被赋予None作为值,这就是它不能通过if语句的真值检验的原因。<br /><br /><br />- 帮助信息有点不同。<br />- 当使用--verbosity选项时,还必须指定一些值,任何值。<br /> || The above example accepts arbitrary integer values for --verbosity, but for our simple program, only two values are actually useful, True or False. Let’s modify the code accordingly: | 上面的例子为--verbosity接受任意的整数值,但对于我们的简单程序,实际上只有两个值是有用的,即True或False。让我们相应地修改代码。 || ```pythonimport 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")
| | | And the output: | 输出结果 | | ```shell $ python3 prog.py —verbose verbosity turned on $ python3 prog.py —verbose 1 usage: prog.py [-h] [—verbose] prog.py: error: unrecognized arguments: 1 $ python3 prog.py —help usage: prog.py [-h] [—verbose]
options: -h, —help show this help message and exit —verbose increase output verbosity
| || Here is what is happening:<br />- The option is now more of a flag than something that requires a value. We even changed the name of the option to match that idea. Note that we now specify a new keyword, action, and give it the value "store_true". This means that, if the option is specified, assign the value True to args.verbose. Not specifying it implies False.<br />- It complains when you specify a value, in true spirit of what flags actually are.<br />- Notice the different help text.<br /> | 以下是正在发生的事情。<br />- 该选项现在更像是一个标志,而不是需要一个值的东西。我们甚至改变了选项的名称来配合这个想法。请注意,我们现在指定了一个新的关键字,action,并给它一个值 "store_true"。这意味着,如果指定了这个选项,就给args.verbose赋值为True。不指定它就意味着是假的。<br /><br /><br /><br />- 当你指定了一个值时,它就会抱怨,这是对标志实际的真实精神。<br />- 注意不同的帮助文本。<br /> |<a name="WYVue"></a>### 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: | 如果您熟悉命令行的用法,您会注意到我还没有涉及到选项的简短版本主题。很简单: || --- | --- || ```pythonimport 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: | 输出结果 | | ```shell $ python3 prog.py -v verbosity turned on $ python3 prog.py —help usage: prog.py [-h] [-v]
options: -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. | 请注意,新功能也反映在帮助文本中。 |<a name="ynlHK"></a>## Combining Positional and Optional arguments| Our program keeps growing in complexity: | 我们程序越来越复杂 || --- | --- || ```pythonimport 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(f"the square of {args.square} equals {answer}")else:print(answer)
| | | And now the output: | 输出结果 | | ```shell $ python3 prog.py usage: prog.py [-h] [-v] square prog.py: error: the following arguments are required: square $ python3 prog.py 4 16 $ python3 prog.py 4 —verbose the square of 4 equals 16 $ python3 prog.py —verbose 4 the square of 4 equals 16
| || <br />- We’ve brought back a positional argument, hence the complaint.<br />- Note that the order does not matter.<br /> | <br />- 我们带回了一个位置性的论点,因此提出了申诉。<br />- 请注意,顺序并不重要。<br /> || How about we give this program of ours back the ability to have multiple verbosity values, and actually get to use them: | 不如我们把我们的这个程序还给它,让它能够有多个粗略的数值,并真正地去使用它们。 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("square", type=int,help="display a square of a given number")parser.add_argument("-v", "--verbosity", type=int,help="increase output verbosity")args = parser.parse_args()answer = args.square**2if args.verbosity == 2:print(f"the square of {args.square} equals {answer}")elif args.verbosity == 1:print(f"{args.square}^2 == {answer}")else:print(answer)
| | | And the output: | 输出结果 | | ```shell $ python3 prog.py 4 16 $ python3 prog.py 4 -v usage: prog.py [-h] [-v VERBOSITY] square prog.py: error: argument -v/—verbosity: expected one argument $ python3 prog.py 4 -v 1 4^2 == 16 $ python3 prog.py 4 -v 2 the square of 4 equals 16 $ python3 prog.py 4 -v 3 16
| || These all look good except the last one, which exposes a bug in our program. Let’s fix it by restricting the values the --verbosity option can accept: | 这些看起来都不错,除了最后一个,它暴露了我们程序中的一个错误。让我们通过限制--verbosity选项可以接受的值来解决这个问题。 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("square", type=int,help="display a square of a given number")parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],help="increase output verbosity")args = parser.parse_args()answer = args.square**2if args.verbosity == 2:print(f"the square of {args.square} equals {answer}")elif args.verbosity == 1:print(f"{args.square}^2 == {answer}")else:print(answer)
| | | And the output: | 运行结果 | | ```shell $ python3 prog.py 4 -v 3 usage: prog.py [-h] [-v {0,1,2}] square prog.py: error: argument -v/—verbosity: invalid choice: 3 (choose from 0, 1, 2) $ python3 prog.py 4 -h usage: prog.py [-h] [-v {0,1,2}] square
positional arguments: square display a square of a given number
options: -h, —help show this help message and exit -v {0,1,2}, —verbosity {0,1,2} increase output verbosity
| || Note that the change also reflects both in the error message as well as the help string. | 请注意,更改还反映在错误消息和帮助字符串中。 || Now, let’s use a different approach of playing with verbosity, which is pretty common. It also matches the way the CPython executable handles its own verbosity argument (check the output of python --help): | 现在,让我们用一种不同的方法来玩弄verbosity,这是很常见的。它也符合CPython可执行文件处理自己的verbosity参数的方式(查看python --help的输出)。 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("square", type=int,help="display the square of a given number")parser.add_argument("-v", "--verbosity", action="count",help="increase output verbosity")args = parser.parse_args()answer = args.square**2if args.verbosity == 2:print(f"the square of {args.square} equals {answer}")elif args.verbosity == 1:print(f"{args.square}^2 == {answer}")else:print(answer)
| | | We have introduced another action, “count”, to count the number of occurrences of specific options. | 我们引入了另一个动作,”计数”,来计算特定选项的出现次数。 | | ```shell $ python3 prog.py 4 16 $ python3 prog.py 4 -v 4^2 == 16 $ python3 prog.py 4 -vv the square of 4 equals 16 $ python3 prog.py 4 —verbosity —verbosity the square of 4 equals 16 $ python3 prog.py 4 -v 1 usage: prog.py [-h] [-v] square prog.py: error: unrecognized arguments: 1 $ python3 prog.py 4 -h usage: prog.py [-h] [-v] square
positional arguments: square display a square of a given number
options: -h, —help show this help message and exit -v, —verbosity increase output verbosity $ python3 prog.py 4 -vvv 16
| || <br />- Yes, it’s now more of a flag (similar to action="store_true") in the previous version of our script. That should explain the complaint.<br />- It also behaves similar to “store_true” action.<br />- Now here’s a demonstration of what the “count” action gives. You’ve probably seen this sort of usage before.<br />- And if you don’t specify the -v flag, that flag is considered to have None value.<br />- As should be expected, specifying the long form of the flag, we should get the same output.<br />- Sadly, our help output isn’t very informative on the new ability our script has acquired, but that can always be fixed by improving the documentation for our script (e.g. via the help keyword argument).<br />- That last output exposes a bug in our program.<br />Let’s fix: | <br />- 是的,在我们脚本的前一个版本中,它现在更像是一个标志(类似于action="store_true")。这应该可以解释这个抱怨。<br /><br /><br />- 它的行为也与 "store_true "动作类似。<br /><br /><br />- 现在来演示一下 "count "动作所带来的效果。你可能以前见过这种用法。<br /><br /><br />- 如果你没有指定-v标志,该标志被认为是无值的。<br />- 正如应该预料的那样,指定该标志的长形式,我们应该得到同样的输出。<br /><br /><br />- 遗憾的是,我们的帮助输出对于我们的脚本所获得的新能力并没有什么信息,但这总是可以通过改进我们脚本的文档(例如通过帮助关键字参数)来解决。<br /><br /><br />- 最后一个输出暴露了我们程序中的一个错误。<br />让我们修复它 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("square", type=int,help="display a square of a given number")parser.add_argument("-v", "--verbosity", action="count",help="increase output verbosity")args = parser.parse_args()answer = args.square**2# bugfix: replace == with >=if args.verbosity >= 2:print(f"the square of {args.square} equals {answer}")elif args.verbosity >= 1:print(f"{args.square}^2 == {answer}")else:print(answer)
| |
| And this is what it gives: | 输出结果 |
| ```shell
$ python3 prog.py 4 -vvv
the square of 4 equals 16
$ python3 prog.py 4 -vvvv
the square of 4 equals 16
$ python3 prog.py 4
Traceback (most recent call last):
File “prog.py”, line 11, in
| || <br />- First output went well, and fixes the bug we had before. That is, we want any value >= 2 to be as verbose as possible.<br />- Third output not so good.<br />Let’s fix that bug: | <br />- 第一次输出很顺利,并且修复了我们之前的错误。就是说,我们希望任何>=2的值都尽可能的啰嗦。<br />- 第三次输出不那么好<br />让我们修复它 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("square", type=int,help="display a square of a given number")parser.add_argument("-v", "--verbosity", action="count", default=0,help="increase output verbosity")args = parser.parse_args()answer = args.square**2if args.verbosity >= 2:print(f"the square of {args.square} equals {answer}")elif args.verbosity >= 1:print(f"{args.square}^2 == {answer}")else:print(answer)
| |
| We’ve just introduced yet another keyword, default. We’ve set it to 0 in order to make it comparable to the other int values. Remember that by default, if an optional argument isn’t specified, it gets the None value, and that cannot be compared to an int value (hence the TypeError exception). | 我们刚刚引入了另一个关键字,default。我们把它设置为0,以使它与其他的int值相比较。
请记住,在默认情况下,如果没有指定一个可选参数,它就会得到None值,而这不能与一个int值进行比较(因此会出现TypeError异常)。 |
| ```shell
$ python3 prog.py 4
16
| || You can go quite far just with what we’ve learned so far, and we have only scratched the surface. The [argparse](https://docs.python.org/3/library/argparse.html#module-argparse) module is very powerful, and we’ll explore a bit more of it before we end this tutorial. | 仅凭我们目前所学到的知识,你就可以走得很远,而我们只触及到了表面。<br />argparse模块非常强大,在本教程结束之前,我们将对它进行更多的探索。 |<a name="fot3w"></a>## Getting a little more advanced| What if we wanted to expand our tiny program to perform other powers, not just squares: | 如果我们想把我们的小程序扩展到执行其他的权力,而不仅仅是平方。 || --- | --- || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("x", type=int, help="the base")parser.add_argument("y", type=int, help="the exponent")parser.add_argument("-v", "--verbosity", action="count", default=0)args = parser.parse_args()answer = args.x**args.yif args.verbosity >= 2:print(f"{args.x} to the power {args.y} equals {answer}")elif args.verbosity >= 1:print(f"{args.x}^{args.y} == {answer}")else:print(answer)
| | | Output: | 运行结果: | | ```shell $ python3 prog.py usage: prog.py [-h] [-v] x y prog.py: error: the following arguments are required: x, y $ python3 prog.py -h usage: prog.py [-h] [-v] x y
positional arguments: x the base y the exponent
options: -h, —help show this help message and exit -v, —verbosity $ python3 prog.py 4 2 -v 4^2 == 16
| || Notice that so far we’ve been using verbosity level to _change_ the text that gets displayed. The following example instead uses verbosity level to display _more_ text instead: | 注意,到目前为止,我们一直在使用verbosity级别来改变所显示的文本。<br />下面的例子则使用了verbosity级别来显示更多的文本。 || ```pythonimport argparseparser = argparse.ArgumentParser()parser.add_argument("x", type=int, help="the base")parser.add_argument("y", type=int, help="the exponent")parser.add_argument("-v", "--verbosity", action="count", default=0)args = parser.parse_args()answer = args.x**args.yif args.verbosity >= 2:print(f"Running '{__file__}'")if args.verbosity >= 1:print(f"{args.x}^{args.y} == ", end="")print(answer)
| | | Output: | 运行结果 | | ```shell $ python3 prog.py 4 2 16 $ python3 prog.py 4 2 -v 4^2 == 16 $ python3 prog.py 4 2 -vv Running ‘prog.py’ 4^2 == 16
| |<a name="qhVzr"></a>### Conflicting options| So far, we have been working with two methods of an [argparse.ArgumentParser](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser) instance. Let’s introduce a third one, `add_mutually_exclusive_group()`. It allows for us to specify options that conflict with each other. Let’s also change the rest of the program so that the new functionality makes more sense: we’ll introduce the --quiet option, which will be the opposite of the --verbose one: | 到目前为止,我们一直在使用argparse.ArgumentParser实例的两个方法。让我们来介绍第三个方法,add_mutually_exclusive_group()。<br />它允许我们指定那些相互冲突的选项。让我们也改变一下程序的其他部分,以便使新的功能更有意义:我们将引入--quiet选项,它将与--verbose选项相反。 || --- | --- || ```pythonimport argparseparser = argparse.ArgumentParser()group = parser.add_mutually_exclusive_group()group.add_argument("-v", "--verbose", action="store_true")group.add_argument("-q", "--quiet", action="store_true")parser.add_argument("x", type=int, help="the base")parser.add_argument("y", type=int, help="the exponent")args = parser.parse_args()answer = args.x**args.yif args.quiet:print(answer)elif args.verbose:print(f"{args.x} to the power {args.y} equals {answer}")else:print(f"{args.x}^{args.y} == {answer}")
| | | Our program is now simpler, and we’ve lost some functionality for the sake of demonstration. Anyways, here’s the output: | 我们的程序现在更简单了,为了演示,我们失去了一些功能。总之,这里是输出结果。 | | ```shell $ python3 prog.py 4 2 4^2 == 16 $ python3 prog.py 4 2 -q 16 $ python3 prog.py 4 2 -v 4 to the power 2 equals 16 $ python3 prog.py 4 2 -vq usage: prog.py [-h] [-v | -q] x y prog.py: error: argument -q/—quiet: not allowed with argument -v/—verbose $ python3 prog.py 4 2 -v —quiet usage: prog.py [-h] [-v | -q] x y prog.py: error: argument -q/—quiet: not allowed with argument -v/—verbose
| || That should be easy to follow. I’ve added that last output so you can see the sort of flexibility you get, i.e. mixing long form options with short form ones.<br />Before we conclude, you probably want to tell your users the main purpose of your program, just in case they don’t know: | 这应该是很容易理解的。我添加了最后一个输出,这样你就可以看到你得到的灵活性,也就是说,将长式选项和短式选项混合起来。<br /><br />在我们结束之前,你可能想告诉你的用户你的程序的主要目的,以防他们不知道。 || ```pythonimport argparseparser = argparse.ArgumentParser(description="calculate X to the power of Y")group = parser.add_mutually_exclusive_group()group.add_argument("-v", "--verbose", action="store_true")group.add_argument("-q", "--quiet", action="store_true")parser.add_argument("x", type=int, help="the base")parser.add_argument("y", type=int, help="the exponent")args = parser.parse_args()answer = args.x**args.yif args.quiet:print(answer)elif args.verbose:print("{} to the power {} equals {}".format(args.x, args.y, answer))else:print("{}^{} == {}".format(args.x, args.y, answer))
| | | Note that slight difference in the usage text. Note the [-v | -q], which tells us that we can either use -v or -q, but not both at the same time: | 注意使用文本中的细微差别。注意[-v | -q],它告诉我们,我们可以使用-v或-q,但不能同时使用两者。 | | ```shell $ python3 prog.py —help usage: prog.py [-h] [-v | -q] x y
calculate X to the power of Y
positional arguments: x the base y the exponent
options: -h, —help show this help message and exit -v, —verbose -q, —quiet ``` | |
Conclusion
| The argparse module offers a lot more than shown here. Its docs are quite detailed and thorough, and full of examples. Having gone through this tutorial, you should easily digest them without feeling overwhelmed. | argparse模块提供了比这里更多的东西。它的文档相当详细和彻底,而且充满了例子。 通过本教程的学习,你应该很容易消化它们,而不会感到不知所措。 |
|---|---|
