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/pejsidney/p/12258860.html