Writing better main() functions
Wendy linked to an older post by Guido about how to make your Python main() functions a little better and more flexible. Here’s the basic idea:
Summary
For Python programmers, I’ve got some suggestions on how to write a main() function that’s easy to invoke in other contexts, e.g. from the interactive Python prompt when you feel like experimenting.
The first tip is to allow main() to take some arguments. Then if arguments are set, store them in argv and use that for any necessary getopt() calls. Here’s his code example:
def main(argv=None):
if argv is None:
argv = sys.argv
The other tip is to call sys.exit(main()) as a more graceful way of ending your scripts. It’s a little more complicated, and I’m not entirely convinced it’s necessary, but a decent idea.
I should really browse through more of Guido’s older posts. Lots of good advice in there for those who are new to the language.
