在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能。目前有短选项和长选项两种格式。短选项格式为"-"加上单个字母选项;长选项为"--"加上一个单词。长格式是在Linux下引入的。许多Linux程序都支持这两种格式。在Python中提供了getopt模块很好的实现了对这两种用法的支持,而且使用简单。

取得命令行参数
  在使用之前,首先要取得命令行参数。使用sys模块可以得到命令行参数。
import sys
print sys.argv

  然后在命令行下敲入任意的参数,如:
python get.py -o t --help cmd file1 file2

  结果为:
['get.py', '-o', 't', '--help', 'cmd', 'file1', 'file2']

  可见,所有命令行参数以空格为分隔符,都保存在了sys.argv列表中。其中第1个为脚本的文件名。

选项的写法要求
  对于短格式,"-"号后面要紧跟一个选项字母。如果还有此选项的附加参数,可以用空格分开,也可以不分开。长度任意,可以用引号。如以下是正确的:
-o
-oa
-obbbb
-o bbbb
-o "a b"
  对于长格式,"--"号后面要跟一个单词。如果还有些选项的附加参数,后面要紧跟"=",再加上参数。"="号前后不能有空格。如以下是正确的:

--help=file1

  而这些是不正确的:
-- help=file1
--help =file1
--help = file1
--help= file1

如何用getopt进行分析
  使用getopt模块分析命令行参数大体上分为三个步骤:

1.导入getopt, sys模块
2.分析命令行参数
3.处理结果

  第一步很简单,只需要:
import getopt, sys

  第二步处理方法如下(以Python手册上的例子为例):
try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])
except getopt.GetoptError:
    # print help information and exit:

1. 处理所使用的函数叫getopt(),因为是直接使用import导入的getopt模块,所以要加上限定getopt才可以。
2. 使用sys.argv[1:]过滤掉第一个参数(它是执行脚本的名字,不应算作参数的一部分)。
3. 使用短格式分析串"ho:"。当一个选项只是表示开关状态时,即后面不带附加参数时,在分析串中写入选项字符。当选项后面是带一个附加参数时,在分析串中写入选项字符同时后面加一个":"号。所以"ho:"就表示"h"是一个开关选项;"o:"则表示后面应该带一个参数。
4. 使用长格式分析串列表:["help", "output="]。长格式串也可以有开关状态,即后面不跟"="号。如果跟一个等号则表示后面还应有一个参数。这个长格式表示"help"是一个开关选项;"output="则表示后面应该带一个参数。
5. 调用getopt函数。函数返回两个列表:opts和args。opts为分析出的格式信息。args为不属于格式信息的剩余的命令行参数。opts是一个两元组的列表。每个元素为:(选项串,附加参数)。如果没有附加参数则为空串''。
6. 整个过程使用异常来包含,这样当分析出错时,就可以打印出使用信息来通知用户如何使用这个程序。

  如上面解释的一个命令行例子为:
'-h -o file --help --output=out file1 file2'

  在分析完成后,opts应该是:
[('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]

  而args则为:
['file1', 'file2']

  第三步主要是对分析出的参数进行判断是否存在,然后再进一步处理。主要的处理模式为:
for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    if o in ("-o", "--output"):
        output = a

  使用一个循环,每次从opts中取出一个两元组,赋给两个变量。o保存选项参数,a为附加参数。接着对取出的选项参数进行处理。(例子也采用手册的例子)

http://docs.python.org/2/library/getopt.html

15.6.getopt— C-style parser for command line options

Note

Thegetoptmodule is a parser for command line options whose API is designed to be familiar to users of the Cgetopt()function. Users who are unfamiliar with the Cgetopt()function or who would like to write less code and get better help and error messages should consider using the argparse module instead.

This module helps scripts to parse the command line arguments insys.argv. It supports the same conventions as the Unixgetopt()function (including the special meanings of arguments of the form ‘-‘ and ‘--‘). Long options similar to those supported by GNU software may be used as well via an optional third argument.

A more convenient, flexible, and powerful alternative is the optparse module.

This module provides two functions and an exception:

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

Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this meanssys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unixgetopt()uses).

Note

Unlike GNUgetopt(), after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.

long_options, if specified, must be a list of strings with the names of the long options which should be supported. The leading'--'characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('='). Optional arguments are not supported. To accept only long options,options should be an empty string. Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if long_optionsis['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised.

The return value consists of two elements: the first is a list of(option, value)pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g.,'-x') or two hyphens for long options (e.g.,'--long-option'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed.

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

This function works like getopt(), except that GNU style scanning mode is used by default. This means that option and non-option arguments may be intermixed. The getopt() function stops processing options as soon as a non-option argument is encountered.

If the first character of the option string is ‘+’, or if the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered.

New in version 2.3.

exception  getopt.GetoptError

This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. The argument to the exception is a string indicating the cause of the error. For long options, an argument given to an option which does not require one will also cause this exception to be raised. The attributesmsgandoptgive the error message and related option; if there is no specific option to which the exception relates,optis an empty string.

Changed in version 1.6: Introduced GetoptError as a synonym for error.

exception  getopt.errorAlias for  GetoptError ; for backward compatibility.

An example using only Unix style options:

>>> 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']

Using long option names is equally easy:

>>> 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']

In a script, typical usage is something like this:

import getopt, sysdef 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 = Noneverbose = Falsefor o, a in opts:if o == "-v":verbose = Trueelif o in ("-h", "--help"):usage()sys.exit()elif o in ("-o", "--output"):output = aelse:assert False, "unhandled option"# ...if __name__ == "__main__":main()

Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the argparse module:

import argparseif __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 ..

getopt在Python中的使用相关推荐

  1. python中getopt函数_Python中getopt()函数的使用

    在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能.目前有短选项和长选项两种格式.短选项格式为"-"加上单个字母选项:长选项为"--"加 ...

  2. python中getopt函数_python getopt模块使用方法

    python中 getopt 模块,是专门用来处理命令行参数的 getop标准格式: 函数getopt(args, shortopts, longopts = []) shortopts 是短参数   ...

  3. Python中getopt()函数的使用

    在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能.目前有短选项和长选项两种格式.短选项格式为"-"加上单个字母选项:长选项为"--"加 ...

  4. python中getopt函数详解

    在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能.目前有短选项和长选项两种格式.短选项格式为"-"加上单个字母选项:长选项为"--"加 ...

  5. Python中getopt函数用法

    参考文献 Python中getopt()函数的使用 简述 对于Python使用命令行的方式去运行Python时候,想要添加各种参数,而想要比较合理的去得到这些参数,就需要使用到Python中的geto ...

  6. python 命令行参数-python中命令行参数

    python中有一个模块sys,sys.argv这个属性提供了对命令行参数的访问.命令行参数是调用某个程序时除程序名外的其他参数. sys.argv是命令行参数的列表 len(sys.argv)是命令 ...

  7. python调用perl_在Perl、Shell和Python中传参与输出帮助文档

    本文同步发表于简书平台中 基于本人对多种编程语言的粗浅了解,不论是哪种编程语言它的参数传递方式主要分为下面两类:直接传递(以Perl为例进行说明) 在调用脚本时,直接传递参数,如:./script.p ...

  8. python中max函数用法_Python中max函数用法实例分析

    Python中max函数用法实例分析 更新时间:2015年07月17日 15:45:09 作者:优雅先生 这篇文章主要介绍了Python中max函数用法,实例分析了Python中max函数的功能与使用 ...

  9. shell执行perl_【编程技巧(一)】在Perl、Shell和Python中传参与输出帮助文档

    社会你明哥,人狠话又多![小明的碎碎念]与你不见不散!作为一名搞数据的生物狗,咱们是生物狗中代码写得最六的,程序员中生物学得最好的--大家没意见吧,有意见请憋着 跟随小明的步伐,让我们开开心心地写Bu ...

最新文章

  1. 在centos上安装最新的glibc
  2. 关于微型计算机的ppt,微型计算机基础知识.ppt
  3. 30年前过气老论文,为何能催生革命全球的CNN框架?
  4. utorrent设置上传速度_utorrent下载速度慢怎样设置 utorrent常用设置图文教程
  5. VTK:可视化之ColorActorEdges
  6. 信息学奥赛一本通(C++)在线评测系统——基础(一)C++语言——1080:余数相同问题
  7. SpringBoot使用Jsp
  8. WebRTC直播技术方案
  9. 等保要求的 linux 系统扫描脚本
  10. mysql 驱动指令_Mysql的驱动包如何发送指令给MYSQL SERVER
  11. 春晚红包:史上最难开卷考试,快手交卷了
  12. [转]小D课堂 - 零基础入门SpringBoot2.X到实战_汇总
  13. android7.1.2 xposed,安卓7.1 xposed框架
  14. 电脑测试耗电量软件,有测验电脑耗电量的软件么 ?
  15. android外设按键,Android 外接键盘的按键处理 .
  16. [OCCT] OCC官方示例介绍
  17. 什么是SCSI硬盘?
  18. SAS(十二)PROC步
  19. cmos sensor camera banding 现象发生原因及相关问题
  20. 基于OpenCV的视频场景切割神器

热门文章

  1. java future用法_纯干货:Java学习过程中的21个知识点和技术点
  2. python3 x默认使用的编码_python3默认使用什么编码
  3. python服务器搭建 实战_实战讲解:如何用Python搭建一个服务器
  4. linux kvm安装win7,详解在 KVM 上安装 Win7 虚拟机
  5. 工业交换机常用术语及常见知识点汇总
  6. 【渝粤教育】广东开放大学 云计算技术与应用 形成性考核
  7. 【渝粤题库】陕西师范大学164205 ERP原理及应用 作业(专升本)
  8. 【渝粤题库】广东开放大学 面向对象方法精粹 形成性考核
  9. 2021年春季学期期末统一考试 西方经济学(本) 试题
  10. html如何与php,html页面怎么跟php文件连接