Python main() functions


/ Published in: Python
Save to your folder(s)

Guido Van Rossum talks about his recipe for a useful main() function.


Copy this code and paste it in your HTML
  1. import sys
  2. import getopt
  3.  
  4. class Usage(Exception):
  5. def __init__(self, msg):
  6. self.msg = msg
  7.  
  8. def main(argv=None):
  9. if argv is None:
  10. argv = sys.argv
  11. try:
  12. try:
  13. opts, args = getopt.getopt(argv[1:], "h", ["help"])
  14. except getopt.error, msg:
  15. raise Usage(msg)
  16. # more code, unchanged
  17. except Usage, err:
  18. print >>sys.stderr, err.msg
  19. print >>sys.stderr, "for help use --help"
  20. return 2
  21.  
  22. if __name__ == "__main__":
  23. sys.exit(main())

URL: http://www.artima.com/weblogs/viewpost.jsp?thread=4829

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.