argparse 教程

作者 :

Tshepang Mbambo

此教程旨在温和介绍 argparse ,推荐的 Python 标准库命令行剖析模块。

注意

有 2 个其它模块完成相同任务,也就是 getopt (相当于 getopt() 来自 C 语言) 和弃用 optparse 。另请注意 argparse 基于 optparse ,因此在用法术语上非常相似。

概念

让我们展示在此前言教程中要探索的一类功能,通过利用 ls 命令:

$ 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.
...