python main函数写法_python中main()函数写法

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

copycode.gif

#!/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())

copycode.gif

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

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

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

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

copycode.gif

>>> 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']

copycode.gif

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

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