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

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

Jordan at, "Greenberg <", "greenbergj\"", at, ">" writes:

> jezonthenet at 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:


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
    except SystemExit, e:
        exitcode = e.code

    return exitcode

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

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. 0.0.23 -  Simon Huggins <huggie at>  Released under GPL
Copyright (C) 1999-2002 Project Purple.

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