1,使用模块getopt
看个例子:
import getopt,sys __version__ = '1.0.0' _debug = 0 def main(): try: opts,args = getopt.getopt(sys.argv[1:], 'ho:vd', ['help','output=']) except getopt.GetoptError,e: print str(e) usage() sys.exit() output = False for o,a in opts: if o == '-v': print 'version:' + __version__ elif o == '-d': global _debug _debbug = 1 elif o in ("-h","--help"): usage() sys.exit() elif o in ("-o","--output="): output = a print output else: assert False,"unhandled Exception" def usage(): print 'usage' if __name__ == '__main__': main()
2,使用模块optparse
python.org上面是这样介绍optparse的:
optparse is a more convenient,flexible,and powerful library for parsing command-line options then the old getpopt moudle.optparse uses a more declarative style of command-line parsing:you create an instance of OptionParser,populate it with options, and parse the command line.optparse allows users to specify options in the conventional GNU/POSIX syntax,and additionally generates help message for you.(http://docs.python.org/2.6/library/optparse.html#module-optparse)
这个模块我个人觉得就是简化了再写一个usage函数。不过这个模块在python 的 version 2.7 以后就不推荐使用了(Deprecated since version 2.7: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.)
3,使用模块argparse
http://docs.python.org/2/library/argparse.html#module-argparse
我个人已经非常习惯使用第一个模块getopt了,觉得用着习惯了,基本的需求也能够满足。