非常教程

Python参考手册

操作系统 | Operating System

getopt

源代码: Lib / getopt.py

注意

getopt模块是用于命令行选项的解析器,其API旨在为C getopt()函数的用户所熟悉。不熟悉C getopt()函数的用户,或者希望编写更少代码并获得更好的帮助和错误消息的用户应考虑使用该argparse模块。

该模块帮助脚本解析命令行参数sys.argv。它支持与Unix getopt()函数相同的约定(包括' -'和' --' 形式的参数的特殊含义)。通过可选的第三个参数,也可以使用类似于GNU软件支持的长选项。

该模块提供了两个功能和一个例外:

getopt.getopt(args, options[, long_options])

分析命令行选项和参数列表。args是要解析的参数列表,没有对正在运行的程序的引用。通常,这意味着sys.argv[1:]选项是脚本想要识别的选项字符串,其中需要参数后跟冒号的选项(':'即,与Unix getopt()使用的格式相同)。

Note

与GNU不同getopt(),在非选项参数之后,所有进一步的参数也被认为是非选项。这与非GNU Unix系统的工作方式类似。

long_options(如果指定)必须是一个字符串列表,其中应该支持长选项的名称。主要'--'字符不应包含在选项名称中。需要参数的长选项后面应该跟一个等号('=')。可选参数不受支持。要只接受长选项,选项应该是一个空字符串。只要提供的选项名称前缀与接受的选项之一完全匹配,就可以识别命令行上的长选项。例如,如果long_options['foo', 'frob'],该选项--fo将匹配为--foo,但--f不会唯一匹配,因此GetoptError会被提出。

返回值由两个元素组成:第一个是(option, value)成对的列表; 第二个是选项列表被剥离后留下的程序参数列表(这是一个后面的args片段)。每个返回的选项和值对具有作为其第一个元素的选项,其前缀为短选项(例如'-x')的连字符或长选项的两个连字符(例如'--long-option'),选项参数作为其第二个元素或空字符串,如果该选项没有参数。这些选项按照与它们相同的顺序出现在列表中,从而允许多次出现。多头和空头期权可能会混合。

getopt.gnu_getopt(args, options[, long_options])

此功能的工作原理与getopt()默认情况下使用的GNU风格扫描模式不同。这意味着选项和非选项参数可能会混在一起。getopt()只要遇到非选项参数,该函数立即停止处理选项。

如果选项字符串的第一个字符是'+',或者如果POSIXLY_CORRECT设置了环境变量,则只要遇到非选项参数,选项处理就会停止。

2.3版本的新功能。

exception getopt.GetoptError

当在参数列表中找到无法识别的选项或者需要参数的选项不存在时,会引发此问题。异常的参数是一个指示错误原因的字符串。对于长期选项,给一个不需要一个选项的参数也会导致这个异常被提出。属性msgopt给出错误信息和相关选项; 如果没有与异常相关的特定选项,opt则为空字符串。

在版本1.6中更改:GetoptError作为一个同义词引入error

exception getopt.error

别名GetoptError; 为了向后兼容。

仅使用Unix样式选项的示例:

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

使用长选项名称同样简单:

>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
...     'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']

在脚本中,典型用法如下所示:

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()

请注意,通过使用argparse模块,可以使用更少的代码和更多的信息帮助和错误消息来生成等效的命令行界面:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output')
    parser.add_argument('-v', dest='verbose', action='store_true')
    args = parser.parse_args()
    # ... do something with args.output ...
    # ... do something with args.verbose ..

Module argparse 可选的命令行选项和参数解析库。

Python

Python 是一种面向对象的解释型计算机程序设计语言,由荷兰人 Guido van Rossum 于1989年发明,第一个公开发行版发行于1991年。 Python 是纯粹的自由软件, 源代码和解释器 CPython 遵循 GPL 协议。Python 语法简洁清晰,特色之一是强制用空白符( white space )作为语句缩进。

主页 https://www.python.org/
源码 https://github.com/python/cpython
版本 2.7
发布版本 2.7.13

Python目录

1.内置常量 | Built-in Constants
2.内置例外 | Built-in Exceptions
3.内置函数 | Built-in Functions
4.内置类型 | Built-in Types
5.编译器 | Compiler
6.加密 | Cryptography
7.数据压缩 | Data Compression
8.数据持久性 | Data Persistence
9.数据类型 | Data Types
10.调试和分析 | Debugging & Profiling
11.开发工具 | Development Tools
12.文件和目录访问 | File & Directory Access
13.文件格式 | File Formats
14.构架 | Frameworks
15.输入 | Importing
16.输入/输出 | Input/ouput
17.国际化 | Internationalization
18.网络 | Internet
19.网络数据 | Internet Data
20.翻译 | Interpreters
21.语言 | Language
22.记录 | Logging
23.Mac OS
24.MS Windows
25.多媒体 | Multimedia
26.联网 | Networking
27.数字与数学 | Numeric & Mathematical
28.操作系统 | Operating System
29.可选操作系统 | Optional Operating System
30.限制执行 | Restricted Execution
31.运行 | Runtime
32.SGI IRIX
33.软件包装与分销 | Software Packaging & Distribution
34.字符串 | String
35.结构化标记 | Structured Markup
36.Tk
37.Unix
38.Python 简介
39.Python pass 语句
40.Python 循环嵌套
41.Python 运算符
42.Python log10() 函数
43.Python log() 函数
44.Python floor() 函数
45.Python fabs() 函数
46.Python exp() 函数
47.Python cmp() 函数
48.Python ceil() 函数
49.Python abs() 函数
50.Python Number(数字)
51.Python pow() 函数
52.Python modf() 函数
53.Python min() 函数
54.Python max() 函数
55.Python asin() 函数
56.Python acos() 函数
57.Python uniform() 函数
58.Python shuffle() 函数
59.Python seed() 函数
60.Python random() 函数
61.Python randrange() 函数
62.Python choice() 函数
63.Python sqrt() 函数
64.Python round() 函数
65.Python radians() 函数
66.Python degrees() 函数
67.Python tan() 函数
68.Python sin() 函数
69.Python hypot() 函数
70.Python cos() 函数
71.Python atan2() 函数
72.Python atan() 函数
73.Python 元组
74.Python 列表(List)
75.Python 字符串
76.Python 字典(Dictionary)
77.Python 日期和时间
78.Python 函数
79.Python 模块
80.Python capitalize()方法
81.Python center()方法
82.Python count() 方法
83.Python expandtabs()方法
84.Python endswith()方法
85.Python encode()方法
86.Python decode()方法
87.Python find()方法
88.Python index()方法
89.Python 异常处理
90.Python isspace()方法
91.Python isnumeric()方法
92.Python islower()方法
93.Python isdigit()方法
94.Python isalpha()方法
95.Python isalnum()方法
96.Python isupper()方法
97.Python istitle()方法
98.Python min()方法
99.Python max()方法
100.Python maketrans()方法