Program __main__ function (was: Starting Python... some questions)

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Mar 13 07:06:15 CET 2007


Jordan at bag.python.org, "Greenberg <"@bag.python.org, "greenbergj\""@NOSPAM.xs4all.nl, wit.edu at bag.python.org, ">"@bag.python.org writes:

> jezonthenet at yahoo.com wrote:
> > * Doesn't the __main__() method automatically execute when I run
> > my python program?
>
> No, there is no special __main__ function, to the best of my
> knowledge.

Guido van Rossum has mused on the idiom of the 'main' function in modules:

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

My idiom for this is:

=====
def __main__(argv=None):
    """ Mainline code for this program """

    from sys import argv as sys_argv
    if argv is None:
        argv = sys_argv

    foo = Foo(argv)     # Foo is the main thing I need
    exitcode = None
    try:
        foo.do_the_main_thing()
    except SystemExit, e:
        exitcode = e.code

    return exitcode

if __name__ == "__main__":
    import sys
    exitcode = __main__(argv=sys.argv)
    sys.exit(exitcode)
=====

The reason for the local 'sys' imports is that I can boilerplate this
code and not have to worry about whether the rest of the program
actually uses the 'sys' module.

The reason for parameterising 'argv', but defaulting it to the system
argv, is that I can unit-test the '__main__' function
programmatically, while still letting it pick up the real argv when
the program is run.

Same reason for catching SystemExit, and then going on to call
'sys.exit()' myself: it allows the __main__ function to be unit-tested
easily, while still letting me use 'sys.exit()' in my application code
whenever it makes sense.

Now, when I write unit tests for my program (i.e. a Python module
designed to be run as a command), it can still be imported safely into
my unit tests, and all the code gets covered by test cases except the
three-line stanza at the end.
Htag.pl 0.0.23 -  Simon Huggins <huggie at earth.li>  Released under GPL
Copyright (C) 1999-2002 Project Purple. http://www.earth.li/projectpurple/

Got sigmatch == ^/home/bignose/\.sigs/news.*$

-- 
 \        "The right to search for truth implies also a duty; one must |
  `\     not conceal any part of what one has recognized to be true."  |
_o__)                                               -- Albert Einstein |
Ben Finney




More information about the Python-list mailing list