3

I'm a Python beginner and have successfully gotten my first program with CLI parameters passed in to run. Got lots of help from this Handling command line options.

My question is: Why in Example 5.45 a separate def main(argv) has been used, instead of calling the try/except block within __main__ itself.

Example 5.45

def main(argv):                         
    grammar = "kant.xml"
    try:                                
        opts, args = getopt.getopt(argv, "hg:d", ["help", "grammar="]) 2
    except getopt.GetoptError:
        usage()
        sys.exit(2)                     

...

if __name__ == "__main__":
    main(sys.argv[1:])

Hope someone versed in Python could share your wisdom.

TIA - Ashant

mauris
  • 42,982
  • 15
  • 99
  • 131
euroblaze
  • 306
  • 3
  • 6
  • [This][1] thread has explained this issue in brief details. Hope this help. [1]: http://stackoverflow.com/questions/419163/what-does-if-name-main-do – Aamir Rind Dec 18 '11 at 09:04

2 Answers2

2

There is no strict technical reason, but it is quite idiomatic to keep the code outside functions as short as possible. Specifically, putting the code into the module scope would turn the variables grammar, opts and args into global public variables, even though they are only required inside the main code. Furthermore, using a dedicated main function simplifies unit-testing this function.

Philipp
  • 48,066
  • 12
  • 84
  • 109
1

One advantage of using a main function is that it allows for easy code re-use:

import sys
import script

script.main(sys.argv[1:])
# or, e.g. script.main(['-v', 'file.txt']), etc

Any code in the script's __main__ block won't be run if it is imported as a module. So the main function acts as a simple interface providing access to all the normal functionality of the script. The __main__ block will then usually contain just a single call to main, plus any other non-essential code (such as tests).

Some tips from the author of Python on how to write a good main function can be found here.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336