python中main()函数写法
顶顶大名的Guido van Rossum(Python之父)推荐的main写法:
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 ( [命令行参数列表], ‘短选项’, [长选项列表] )
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> 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']