<jupyter_start><jupyter_text>`argparse`{guilabel}`视频`<iframe id="Python"    title="Python `argparse`"    width="100%"    height="600"    src="https://developer.hs.net/thread/2041">详细介绍可以参考：- [python argparse 用法总结](https://www.jianshu.com/p/a41fbd4919f8)- [Argparse 教程](argparse-tutorial){mod}`argparse`：命令行选项、参数和子命令解析器 基础我们编写最简单的例子：```{literalinclude} examples/argparse/simple.py:language: python```在没有任何选项的情况下运行脚本不会在标准输出显示任何内容。这没有什么用处：<jupyter_code>!python examples/argparse/simple.py<jupyter_output><empty_output><jupyter_text>{option}`--help` 选项，也可缩写为 {option}`-h`，是唯一一个可以直接使用的选项（即不需要指定该选项的内容）：<jupyter_code>!python examples/argparse/simple.py --help<jupyter_output>usage: simple.py [-h]

optional arguments:
  -h, --help  show this help message and exit<jupyter_text>指定其他任何内容都会导致错误。即便如此，我们也能直接得到一条有用的用法信息。<jupyter_code>!python examples/argparse/simple.py --verbose
!python examples/argparse/simple.py foo<jupyter_output>usage: simple.py [-h]
simple.py: error: unrecognized arguments: foo<jupyter_text>位置参数举个例子：```{literalinclude} examples/argparse/echos.py:language: python```运行此程序：<jupyter_code>!python examples/argparse/echos.py<jupyter_output>usage: echos.py [-h] echo
echos.py: error: the following arguments are required: echo<jupyter_text>增加了 {meth}`add_argument` 方法，该方法用于指定程序能够接受哪些命令行选项。在这个例子中，我将选项命名为 `echo`，与其功能一致。现在调用我们的程序必须要指定一个选项：<jupyter_code>!python examples/argparse/echos.py foo<jupyter_output>foo<jupyter_text>查看帮助信息：<jupyter_code>!python examples/argparse/echos.py -h<jupyter_output>usage: echos.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit<jupyter_text>可以给位置参数一些辅助信息：```{literalinclude} examples/argparse/echos_help.py:language: python```<jupyter_code>!python examples/argparse/echos_help.py -h<jupyter_output>usage: echos_help.py [-h] echo

positional arguments:
  echo        echo the string you use here

optional arguments:
  -h, --help  show this help message and exit<jupyter_text>传入的位置参数选项的值默认是作为字符串传递的，可以修改其为其他类型：```{literalinclude} examples/argparse/square.py:language: python```以下是该代码的运行结果：<jupyter_code>!python examples/argparse/square.py 4<jupyter_output>16<jupyter_text>输错类型，会触发异常：<jupyter_code>!python examples/argparse/square.py '4'<jupyter_output>usage: square.py [-h] square
square.py: error: argument square: invalid int value: "'4'"<jupyter_text>当程序在收到错误的无效的输入时，它甚至能在执行计算之前先退出，还能显示很有帮助的错误信息。 可选参数下面看看如何添加可选参数：```{literalinclude} examples/argparse/option.py:language: python```这一程序被设计为当指定 {command}`--verbosity` 选项时显示某些东西，否则不显示。<jupyter_code>!python examples/argparse/option.py --verbosity 1
!python examples/argparse/option.py<jupyter_output><empty_output><jupyter_text>```{hint}如果一个可选参数没有被使用时，相关变量被赋值为 `None`。```<jupyter_code>!python examples/argparse/option.py --help<jupyter_output>usage: option.py [-h] [--verbosity VERBOSITY]

optional arguments:
  -h, --help            show this help message and exit
  --verbosity VERBOSITY
                        increase output verbosity<jupyter_text>上述例子接受任何整数值作为 {command}`--verbosity` 的参数，但对于简单程序而言，只有两个值有实际意义：`True` 或者 `False`。据此修改代码：```{literalinclude} examples/argparse/option_action.py:language: python```现在，这一选项多了一个旗标，而非需要接受一个值的什么东西。我们甚至改变了选项的名字来符合这一思路。注意我们现在指定了一个新的关键词 `action`，并赋值为 `"store_true"`。这意味着，当这一选项存在时，为 `args.verbose` 赋值为 `True`。没有指定时则隐含地赋值为 `False`。<jupyter_code>!python examples/argparse/option_action.py --verbose
!python examples/argparse/option_action.py --verbose 1
!python examples/argparse/option_action.py -h<jupyter_output>usage: option_action.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity<jupyter_text>短选项例如：```{literalinclude} examples/argparse/short.py:language: python```效果就像这样：<jupyter_code>!python examples/argparse/short.py -h
!python examples/argparse/short.py -v<jupyter_output>verbosity turned on<jupyter_text>结合位置参数和可选参数```{literalinclude} examples/argparse/complex1.py:language: python```接着是输出：<jupyter_code>!python examples/argparse/complex1.py
!python examples/argparse/complex1.py 4
!python examples/argparse/complex1.py 4 --verbose<jupyter_output>the square of 4 equals 16<jupyter_text>顺序无关紧要：<jupyter_code>!python examples/argparse/complex1.py --verbose 4<jupyter_output>the square of 4 equals 16<jupyter_text>给程序加上接受多个 `verbosity` 的值，然后实际使用：```{literalinclude} examples/argparse/complex2.py:language: python```<jupyter_code>!python examples/argparse/complex2.py 4
!python examples/argparse/complex2.py 4 -v
!python examples/argparse/complex2.py 4 -v 1
!python examples/argparse/complex2.py 4 -v 2
!python examples/argparse/complex2.py 4 -v 3<jupyter_output>16
{'fraction_non_alphanumeric': 0.13386505712438027, 'fraction_numerical': 0.01164043974994611, 'mean_word_length': 7.689138576779026, 'pattern_counts': {'":': 0, '<': 52, '<?xml version=': 0, '>': 52, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '89835', 'license': 'Apache-2.0', 'n_tokens_mistral': 2098, 'n_tokens_neox': 2160, 'n_words': 251, 'path': 'doc/python-study/basic/argparse.ipynb', 'repo_name': 'xinetzone/d2py', 'size': '4639'}