What the if __name__ == '__main__'does in python and practice of defining python main functions.

What is if __name__ == '__main__' for?

A python file can either be reusable module or be standalone executable script.
When python interpreter reads a python file, it will execute all its executable
statements, no matter it is being executed as standalone script or imported as
reusable module. If we want some of the executable statements to run only when
the module is being run as standalone script (for example, some test functions),
we can move them into if __name__ == '__main__'. When a file is being executed
as standalone script, its __name__ is set to __main__ by python interpreter, so
python interpreter will execute the statements within if __name__ == '__main__'
structure, while when it being imported, its __name__ is the script/module name,
and python interpreter does not run statements within if __name__ == '__main__'.

Defining python main functions

import sys
import getopt

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):
    if argv is None:
        argv = sys.argv
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
             raise Usage(msg)
        # more code, unchanged
    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

if __name__ == "__main__":


Post tagged with: python