Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created July 1, 2016 09:58
Show Gist options
  • Save limboinf/64d07f6eb6a5cd1c50356b36e3aa89f0 to your computer and use it in GitHub Desktop.
Save limboinf/64d07f6eb6a5cd1c50356b36e3aa89f0 to your computer and use it in GitHub Desktop.
Python之父教你写main()函数.
# coding=utf-8
"""
Python之父教你写main()函数
----------------------------------
main()函数使其接受一个可选参数 argv,支持在交互式shell中调用该函数,
我们就可以动态地提供 argv 的值。
让main()函数的返回值指示退出状态(exit status)并且,
main()函数中的sys.exit(n)调用全部变成return n。
定义一个Usage()异常,可以在main()函数最后的except子句捕捉该异常
:copyright: (c) 2016 by fangpeng(@beginman.cn).
:license: MIT, see LICENSE for more details.
"""
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)
for o, a in opts:
if o in ('-h', '--help'):
print __doc__
return 0
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment