python标准库介绍——26 getopt 模块详解

==getopt 模块==


``getopt`` 模块包含用于抽出命令行选项和参数的函数, 
它可以处理多种格式的选项. 如 [Example 2-23 #eg-2-23] 所示.

其中第 2 个参数指定了允许的可缩写的选项. 选项名后的冒号(:) 意味这这个选项必须有额外的参数.

====Example 2-23. 使用 getopt 模块====[eg-2-23]

```
File: getopt-example-1.py

import getopt
import sys

# simulate command-line invocation
# 模仿命令行参数
sys.argv = ["myscript.py", "-l", "-d", "directory", "filename"]

# process options
# 处理选项
opts, args = getopt.getopt(sys.argv[1:], "ld:")

long = 0
directory = None

for o, v in opts:
    if o == "-l":
        long = 1
    elif o == "-d":
        directory = v

print "long", "=", long
print "directory", "=", directory
print "arguments", "=", args

*B*long = 1
directory = directory
arguments = ['filename']*b*
```

为了让 ``getopt`` 查找长的选项, 如 [Example 2-24 #eg-2-24] 所示, 
传递一个描述选项的列表做为第 3 个参数. 如果一个选项名称以等号(=) 结尾, 
那么它必须有一个附加参数.

====Example 2-24. 使用 getopt 模块处理长选项====[eg-2-24]

```
File: getopt-example-2.py

import getopt
import sys

# simulate command-line invocation
# 模仿命令行参数
sys.argv = ["myscript.py", "--echo", "--printer", "lp01", "message"]

opts, args = getopt.getopt(sys.argv[1:], "ep:", ["echo", "printer="])

# process options
# 处理选项
echo = 0
printer = None

for o, v in opts:
    if o in ("-e", "--echo"):
        echo = 1
    elif o in ("-p", "--printer"):
        printer = v

print "echo", "=", echo
print "printer", "=", printer
print "arguments", "=", args

*B*echo = 1
printer = lp01
arguments = ['message']*b*
```

```
[!Feather 注: 我不知道大家明白没, 可以自己试下:
myscript.py -e -p lp01 message
myscript.py --echo --printer=lp01 message
]
```
原文地址:https://www.cnblogs.com/xuchunlin/p/7763736.html