about if __name == '__main__':

Cameron Simpson cs at zip.com.au
Sun Aug 28 19:59:43 EDT 2011


On 28Aug2011 11:56, woooee <woooee at gmail.com> wrote:
| Two main routines, __main__ and main(), is not the usual or the common
| way to do it.  It is confusing and anyone looking at the end of the
| program for statements executed when the program is called will find
| an isolated call to main(), and then have to search the program for
| the statements that should have been at the bottom of the program.

Firstly, as Terry remarked, __main__ is a name, not a function.

Secondly, "search the program for the statements that should have been at the
bottom of the program" isn't how I see it. If I have a module I expect
to be usable from the command line easily it looks like this:

  def main(argv):
    ... command line program logic ...
    return exit_code

  ... all the other module contents ...

  if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

That way the top level command line program logic is at the top of the file
where it is easy to find, not buried in the middle or at the bottom.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

Anarchy is not lack of order. Anarchy is lack of ORDERS.



More information about the Python-list mailing list