getopt在Python中的使用(转)
2015-07-23 19:38
603 查看
在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能。目前有短选项和长选项两种格式。短选项格式为"-"加上单个字母选项;长选项为"--"加上一个单词。长格式是在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为附加参数。接着对取出的选项参数进行处理。(例子也采用手册的例子)
Note
The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() 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 in sys.argv. It supports the same conventions as the Unix getopt() 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 means sys.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 Unix getopt() uses).
Note
Unlike GNU getopt(), 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_options is ['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 attributes msg and opt give the error message and related option; if there is no specific option to which the exception relates, opt is 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:
Using long option names is equally easy:
In a script, typical usage is something like this:
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:
取得命令行参数
在使用之前,首先要取得命令行参数。使用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为附加参数。接着对取出的选项参数进行处理。(例子也采用手册的例子)
15.6. getopt — C-style parser for command line options
NoteThe getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() 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 in sys.argv. It supports the same conventions as the Unix getopt() 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 means sys.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 Unix getopt() uses).
Note
Unlike GNU getopt(), 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_options is ['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 attributes msg and opt give the error message and related option; if there is no specific option to which the exception relates, opt is 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, sys def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) exceptgetopt.GetoptError, 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 = Trueelif o in ("-h", "--help"): usage() sys.exit() elif o in ("-o", "--output"): output = a else: 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 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 ..
相关文章推荐
- python cookielib 登录人人网
- Python的捕虫笔记
- Python的捕虫笔记
- 那些年,我们读过的python!
- Python中的文本处理
- python连接mysql
- 快速启动cmd下的Python---如何使用java运行多条cmd命令
- Python 推断素数
- python基础教程总结11——图形用户界面GUI
- 如何捅破python编程的那层纸之三
- 飞跃式发展的后现代 Python 世界
- python开发_xml.etree.ElementTree_XML文件操作_该模块在操作XML数据是存在安全隐患_慎用
- 提取网址的python练习
- Python开发MySQL数据库(表)克隆工具
- 初识python django, 让我们一起进入python的世界吧
- 实习小记-python 内置函数__eq__函数引发的探索
- 各种Python插件安装包下载地址
- 在 python 使用socket 获取 IP
- Python 时间,日期,时间戳(一)
- python获取本机网卡IP