python getopterror_python getopt

1.使用getopt模块处理Unix模式的命令行选项:

getopt模块用于抽出命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式。

e.g. python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'

import getopt

shortargs = 'f:t'

longargs = ['directory-prefix=', 'format', '--f_long=']

opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

getopt函数的格式是getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] )

短选项名后的冒号(:)表示该选项必须有附加的参数。

长选项名后的等号(=)表示该选项必须有附加的参数。

返回opts和args。

opts是一个参数选项及其value的元组( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )

args是一个除去有用参数外其他的命令行输入 ( 'a', 'b' )

然后遍历opts便可以获取所有的命令行选项及其对应参数了。

for opt, val in opts:

if opt in ( '-f', '--f_long' ):

pass

if ....

使用字典接受命令行的输入,然后再传送字典,可以使得命令行参数的接口更加健壮。

两个来自python2.5 Documentation的例子:

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

python Documentation中也给出了getopt的典型使用方法:

import getopt, sys

def main():

try:

opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])

except getopt.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 = 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()

下面一段程序演示了在getopt下使用Usage()函数、参数字典(默认参数)、短选项、长选项等。

import os

import os.path

import sys

import getopt

def usage():

print '''

py price.py [option][value]...

-h or --help

-w or --wordattr-file="wordattr文件"

-s or --sflog-pricefile="sflog的价格变化文件"

-t or --tmpdir="临时文件的保存目录,默认为./"

-o or --outputfile="完整信息的保存文件,如果不指定,则输出到stdout"

-a or --wordattr-Complement="较新的wordattr去补全信息,缺省为Null,则丢失新广告的信息"

'''

return 0

if ( len( sys.argv ) == 1 ):

print '-h or --help for detail'

sys.exit(1)

shortargs = 'hw:s:t:o:a:'

longargs = ['help', 'wordattr=', 'sflog-pricefile=', 'tmpdir=', 'outputfile=', 'wordattr-Complement=']

opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

if args:

print '-h or --help for detail'

sys.exit(1)

paramdict = {'tmpdir':os.path.abspath(os.curdir), 'outputfile':sys.stdout, 'newwordattr':None }

for opt,val in opts:

if opt in ( '-h', '--help' ):

usage()

continue

if opt in ( '-w', '--wordattr' ):

paramdict['wordattr'] = val

continue

if opt in ( '-s', '--sflog-pricefile' ):

paramdict['pricefile'] = val

continue

if opt in ( '-t', '--tmpdir' ):

paramdict['tmpdir'] = val

continue

if opt in ( '-o', '--outputfile' ):

try:

paramdict['outputfile'] = open(val,'w')

except Exception,e:

#ul_log.write(ul_log.fatal,'%s,%s,@line=%d,@file=%s' \

#%(type(e),str(e),sys._getframe().f_lineno,sys._getframe().f_code.co_filename))

sys.exit(1)

continue

if opt in ( '-a', '--wordattr-Complement' ):

paramdict['newwordattr'] = val

continue

2. 使用optparser模块处理Unix模式的命令行选项:

optparser模块非常的强大,完全体现了python的“如此简单,如此强大”的特性。

import optparse

def getConfig(ini):

import ConfigParser

try:

cfg = ConfigParser.ConfigParser()

cfg.readfp(open(ini))

print cfg.sections()

except:

pass

if __name__=='__main__':

parser = optparse.OptionParser()

parser.add_option(

"-i",

"--ini",

dest="ini",

default="config.ini",

help="read config from INI file",

metavar="INI"

)

parser.add_option(

"-f",

"--file",

dest="filename",

help="write report to FILE",

metavar="FILE"

)

parser.add_option(

"-q",

"--quiet",

dest="verbose",

action="store_false",

default=True,

help="don't print status messages to stdout"

)

(options, args) = parser.parse_args()

getConfig(options.ini)

print args

another usage:

parser = OptionParser(usage='%prog [options] top_dir_name ')

parser.disable_interspersed_args()

parser.add_option('-t', '--top',

dest='topdir', default=".",

help='the top directory to search')

parser.add_option('-o', '--output',

dest='output', default="auto_search_result.txt",

help='save the search result to output file')

parser.add_option('-d', '--debug',

action='store_true', dest='debug', default=False,

help='enable debug output')

(options, args) = parser.parse_args(sys.argv[1:])

variable options.topdir receive the value of args after -t, so

print options.topdir

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值