why a main() function?
Ben Finney
bignose+hates-spam at benfinney.id.au
Mon Sep 18 20:36:11 EDT 2006
Steve Holden <steve at holdenweb.com> writes:
> beliavsky at aol.com wrote:
> > I think I read a suggestion somewhere to wrap the code where a
> > Python script starts in a main() function
> > [...]
> > What are the advantages of doing this?
> >
> Guido van Rossum himself can tell you:
> http://www.artima.com/forums/flat.jsp?forum=106&thread=4829
I read that one a while ago, and now have this in most of my programs:
def __main__(argv=None):
""" Perform the main function of this program """
from sys import argv as sys_argv
if argv is None:
argv = sys_argv
# preparation, e.g. set up environment
exit_code = None
try:
do_the_main_thing(argv) # or whatever the main step is
except SystemError, e:
exit_code = e.code
return exit_code
if __name__ == '__main__':
import sys
exit_code = __main__(sys.argv)
sys.exit(exit_code)
This allows me to import my program as a module, and treat the main
routine as a function (argv as input, exit_code as output), while the
code itself can do sys.exit() without needing to know that it's
wrapped up in a function.
It also encourages me to write code inside do_the_main_thing() that
gets its environment parameterised as input, instead of specifying
sys.argv and the like. This makes the code much easier to unit test.
The name __main__ was chosen because I saw hints some time ago that
Python 3000 might automate some of these semantics for a function with
that name. True or false?
--
\ "Crime is contagious ... if the government becomes a |
`\ lawbreaker, it breeds contempt for the law." -- Justice Louis |
_o__) Brandeis |
Ben Finney
More information about the Python-list
mailing list