We Recommend

Learning Python Learning Python
The authors of Learning Python show you enough essentials of the Python scripting language to enable you to begin solving problems right away, then reveal more powerful aspects of the language one at a time. This approach is sure to appeal to programmers and system administrators who have urgent problems and a preference for learning by semi-guided experimentation.


Posted By

V on 01/31/07


Tagged

main recipe


Versions (?)


Who likes this?

5 people have marked this snippet as a favorite

gedittest
urandom
fukami
pulczynski
taboularasa


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.