python中main()函数写法

顶顶大名的Guido van Rossum(Python之父)推荐的main写法:

#!/usr/bin/python
import sys
import getopt

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
            raise Usage(msg)
    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

if __name__ == "__main__":
    sys.exit(main())

 

getopt模块用于抽出命令行选项和参数,也就是sys.argv。

命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式

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

getopt.getopt ( [命令行参数列表], '短选项', [长选项列表] )

>>> import getopt, sys
>>> arg = '-a -b -c foo -d bar a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'abc:d:' )
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>> arg = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> optlist, args = getopt.getopt( sys.argv[1:], 'x', ['condition=', 'output-file=', 'testing'] )
>>> optlist
[ ('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x','') ]
>>> args
['a1', 'a2']

参考http://www.jb51.net/article/50067.htm

转载于:https://www.cnblogs.com/LarryGen/p/5427102.html

你可能感兴趣的:(python中main()函数写法)