Posted By

V on 01/31/07


Tagged

main recipe


Versions (?)

Who likes this?

7 people have marked this snippet as a favorite

gedittest
urandom
fukami
pulczynski
taboularasa
FSX
ifnull


Python main() functions


 / Published in: Python
 

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

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

  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())

Report this snippet  

You need to login to post a comment.