python命令行参数处理:argparse、optparse和getopt

来源:互联网 发布:企业目录搜索软件 编辑:程序博客网 时间:2024/06/06 14:28

一 命令行参数:

(1)在python中:

*sys.argv:命令行参数的列表。

*len(sys.argv):命令行参数的个数(argc)。

*python中提供了三个模块来辅助处理命令行参数:getopt,optparse和argparse。


(2)术语:

*argument:命令行上的字符串,在python中参数是sys.argv[1:],argv[0]是执行程序的名字。

*option:选项。

*option argument:选项的值,跟在选项后面。格式:-f foo/-ffoo,--file foo/--file=foo。

*position argument:位置参数,选项被处理后剩下的参数。

*required option。


二 getopt模块:

(1)简单用法:

*简单的识别选项以及选项参数,位置参数以列表的形式返回。


三 optparse模块(从2.7开始废弃,建议使用argparse):

(1)简单用法:

*识别选项以及选项参数,可指定复杂的操作,位置参数以列表的形式返回。如下:

from optparse import OptionParserparser=OptionParser()parser.add_option(“-f”, "--file", dest="filename", action="store" help="need a file name")。(options,args)=parser.parse_args()

*使用时-f 选项值或--file选项值。

*action的值默认是“store”,把选项后面的赋给dest代表的值,即filename=选项值。

*optparse自动为程序提供帮助信息,使用方式-h,--help。add_option函数中的help的值作为查看程序帮助信息时可以看到。

*上例程序的帮助信息是:-l filename,--list=filename  need a filename。注意filename就是dest的值,后面的信息就是help的值。

*parse_args():返回两个值,options和args。options是一个字典,其值为{"filename":选项值},可通过options.filename使用选项值;args是一个位置参数的列表,注意区分选项、选项参数以及位置参数。


(2)action的取值:

*store:默认。

*store_true

*store_false

*store_const:store a constant value.

*append:append this option's argument to a list.

*count:increment a counter by one.

*callback:call a specified function.


四 argparse模块:



0 0
原创粉丝点击