getopt在Python中的使用

在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能。目前有短选项长选项两种格式。短选项格式为"-"加上单个字母选项;长选项为"--"加上一个单词。长格式是在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 ..

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/351323.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

大数据的数据采集数据处理_让我们处理大数据

大数据的数据采集数据处理作为开发人员,我们的重点是简单,有效的解决方案,因此,最有价值的原则之一就是“保持简单和愚蠢”。 但是使用Hadoop map-reduce很难坚持这一点。 如果我们要评估多个Map Reduce作业中的数据,我…

怎样正确使用和维护微型计算机,下篇:微型计算机应该怎样进行维护与保养

2. 养成良好的使用维护习惯(1)正确的使用习惯个人使用习惯对计算机的影响很大,首先是要正常开关机,开机的顺序是,先打开外设的电源,然后再开主机电源。关机顺序相反,先关闭主机电源,再关闭外设电源。其道理…

CF :K 一个含n条边的带权无向连通图,q次查询,每次查询两点间的最短距离。...

题意:给你一个含n条边的带权无向连通图,q次查询,每次查询两点间的最短距离。 思路:LCA思维。 设a,b两点间的距离为f(a,b) 则f(a,b)dis[a]dis[b]-2*dis[lca(a,b)]; 由于n条边,因此我们先任取一条边&#xff…

每天一个linux命令(20):find命令之exec

find是我们很常用的一个Linux命令,但是我们一般查找出来的并不仅仅是看看而已,还会有进一步的操作,这个时候exec的作用就显现出来了。 exec解释: -exec 参数后面跟的是command命令,它的终止是以;为结束标志的&#x…

英语作业介绍一项发明计算机,介绍电脑的发明的英语作文

匿名用户1级2008-07-25 回答Simple 1:Different eras of political history are frequently identified with royal dynasties, or great wars and revolutions.Eras in the history of art and architecture may be distinguished by styles such as Renaissance, Gothic, Imp…

Math、Date内置对象方法整理

Math : 内置的对象&#xff08;构造函数&#xff09;静态属性或静态方法。一、Math.PI : 圆周率console.log(Math.PI);二、近似值1. 四舍五入 &#xff1a; Math.round()注: 负数时&#xff0c; < 0.5 舍去 > 0.5 进一console.log(Math.round(4.5)); //5console…

Neo4j:动态添加属性/设置动态属性

我一直在研究一个包含英国国家铁路时刻表的数据集&#xff0c;它们以文本格式为您提供每列火车的出发和到达时间。 例如&#xff0c;可以这样创建代表停止的节点&#xff1a; CREATE (stop:Stop {arrival: "0802", departure: "0803H"})该时间格式不是特…

便利的开发工具-log4cpp快速使用指南

0. 优点 提供应用程序运行上下文&#xff0c;方便跟踪调试&#xff1b; 可扩展的、多种方式记录日志&#xff0c;包括命令行、文件、回卷文件、内存、syslog服务器、Win事件日志等&#xff1b; 可以动态控制日志记录级别&#xff0c;在效率和功能中进行调整&#xff1b; 所有配…

计算机用户账户无法打开浏览器,请问怎么样禁止一个电脑用户使用IE浏览器

为了不使他人随意改变您对浏览器的设置以及对IE的某些功能限制使用&#xff0c;有必要将你的设置选项进行隐藏或禁止使用。过去在Windows 9x系统中&#xff0c;一般是通过修改注册表来实现的&#xff0c;不过这会对系统的安全性带来一定的风险。当您选择了Windows XP后&#xf…

Mask R-CNN论文理解

摘要&#xff1a; Mask RCNN可以看做是一个通用实例分割架构。Mask RCNN以Faster RCNN原型&#xff0c;增加了一个分支用于分割任务。Mask RCNN比Faster RCNN速度慢一些&#xff0c;达到了5fps。可用于人的姿态估计等其他任务&#xff1b;1、Introduction 实例分割不仅要正确的…

doctype html h5,HTML DOCTYPE

前言&#xff1a;DOCTYPE标签在平常书写HTML的时候总是放在首位内容&#xff0c;但是他有什么作用呢。正文&#xff1a;html之中的DOCTYPE书写H5与H4的时候我们引用的使用的DOCTYPE是会有些许不一样的。HTML4的时候我们使用如下格式&#xff1a;>p.s.这里我们说一下H4的几种…

servlet基础_Servlet基础

servlet基础通过本教程&#xff0c;我将尝试使您更接近Java Servlet模型。 在检查servlet规范中定义的类之前&#xff0c;我将解释在开始开发Web应用程序之前需要了解的基本知识。 了解Java Servlet模型 首先&#xff0c;不仅为基于请求和响应编程模型的规范的Web应用程序定义…

纯 CSS 实现高度与宽度成比例的效果

http://zihua.li/2013/12/keep-height-relevant-to-width-using-css/ 转载于:https://www.cnblogs.com/ygm900/p/10443982.html

c++ || && 逻辑短路问题

结论&#xff1a;“或”逻辑前面为1&#xff0c;“与”逻辑前面为0就会发生短路 1——或逻辑短路 include <stdio.h> int main() { int a5,b6,c7,d8,m2,n2; (ma<b)||(nc>d); printf("%d\t%d",m,n); } 输出的结果为1,2.为什么呢&#xff0c;因为a<b&am…

2021年计算机学硕考研c9,【JRs观点】学姐3000字记录考研8个月心得及作息时间表,献给2021考研同学,从二本到C9...

其实自己不会写东西&#xff0c;本文就像记流水账一样记录一下自己考研的过程吧。18年考研&#xff0c;从二本考上自己理想的985&#xff0c;这心中酸楚只有自己能体会&#xff0c;我个人觉得考研考的是坚持、方法、毅力。在这里把自己的一些经历分享给大家。考研成绩421&#…

abstract

Abstract 类 不能实例化Abstract 方法 在父类里定义抽象方法,在子类里定义这个具体的方法,所以它是抽象的.好处 减少复杂度和提高可维护性 抽象类的子类需要实现父类中的抽象方法&#xff0c;否则会报错。转载于:https://www.cnblogs.com/Frances-CY-FKYM/p/10444062.html

Neo4j:使用LOAD CSV检测CSV标头中的恶意空间

上周&#xff0c;我正在帮助某人将CSV文件中的数据加载到Neo4j中&#xff0c;我们在过滤掉其中一列中包含空值的行时遇到了麻烦。 数据如下所示&#xff1a; load csv with headers from "file:///foo.csv" as row RETURN row╒═════════════════…

lib 和 dll 的区别、生成以及使用详解

【目录】 lib dll介绍 生成动态库 调用动态库 生成静态库 调用静态库 首先介绍一下静态库&#xff08;静态链接库&#xff09;、动态库&#xff08;动态链接库&#xff09;的概念&#xff0c;首先两者都是代码共享的方式。 静态库&#xff1a;在链接步骤中&#xff0c;连接器将…

HDU4631Sad Love Story

这道题是用multiset直接维护就行了&#xff08;可是我根本不会multiset) 用一些剪枝就能跑出来 还有 不要爆int #include <set> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const lo…

计算机知识点小报,制作电脑小报的教案

制作电脑小报的教案教学目标&#xff1a;巩固WORD知识&#xff0c;掌握文档间复制&#xff0c;培养学生的创新能力和综合解决问题的能力&#xff0c;加强爱国主义教育。教学重点&#xff1a;提高学生对WORD的熟练程度&#xff0c;掌握文档间的复制操作及文字和图片的排版。教学…