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

python getopterror_python getopt相关推荐

  1. python getopterror_python getopt抛出getopterror选项——mode不能有参数

    当我指定命令行选项时,getopt似乎不起作用,抛出异常,这个名为o.py的文件: import getopt import sys opts,args = getopt.getopt(sys.arg ...

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

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

  3. python getopt_Python getopt

    python getopt Parsing command line arguments is a very common task, python getopt module is one of t ...

  4. Python中getopt函数用法

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

  5. python getopts_linux bash shell 中getopts 命令 和 python 中 getopt 函数的比较总结

    在 python 中有个获取命令行参数的函数叫 getopt(args, shortopts, longopts=[]) 通常我们使用的时候是如下的形式: import sys import geto ...

  6. python getopterror_python3 getopt用法

    python channel_builder.py -s /Users/graypn/ -d /Users/graypn/Documents -m 7 --out=report/xx.html 参数也 ...

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

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

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

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

  9. python中getopt函数详解

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

最新文章

  1. CISCO CCNA RIP
  2. 垃圾回收器机制(二):快速解读GC算法之标记-清除,复制及标记整理-算法
  3. python shelve模块_python常用模块之shelve模块
  4. vue项目和react项目中禁止eslint
  5. .NET Core2.0 使用EF做数据操作
  6. 谈谈lucene的DocValues特性之SortedNumericDocValuesField
  7. MongoDB配置主从同步(二)
  8. APICS与AX的Master Planning(一)--Phantom bill of Material 虚项
  9. Halcon标定系列(1):实现机械手手眼标定项目介绍、9点标定
  10. Flash动画短片制作流程注意点
  11. ros_arduino_bridge功能包集的使用
  12. C语言常见问题(4):Collapsible if statements should be merged
  13. tts文字转语音_最佳文字转语音(TTS)软件程序和在线工具
  14. MySQL Workbench main_menu.xml 文件 可直接粘贴(下)
  15. unity 获取设备的GPS信息
  16. 显示一个立方体的一点透视投影图;(用数组存放正方体的各顶点坐标)。
  17. win10 windows许可证即将过期的解决办法
  18. ms office excel2013教程 - 分类汇总
  19. 判断QQ号码长度是否“合法”?让小白来告诉你
  20. linux下代码写错了怎么更改_谢宝友:手把手教你给Linux内核发patch

热门文章

  1. 嵌入式linux开发,/lib/libc.so.6: version `GLIBC_2.17‘ not found (required by /.../lib/libpaho-mqtt3a.so.1)
  2. 联想笔记本那些有手写功能_联想笔记本那些有手写功能_Windows 8 下笔记本如何实现手写输入...
  3. 第九周 oj 二 ASCII排序
  4. 毕业设计-基于机器视觉的视觉手势识别-OpneCv
  5. https协议【转】
  6. 中国新能源汽车产业十四五应用建设与发展布局研究报告2022版
  7. 完美攻略之雪のとける頃に...雪融化的时候…(雪融化的时刻…)
  8. The Closest M Points
  9. 【转】Hibernate入门之命名策略(naming strategy)详解
  10. imba的bit向量