main

Ben Finney bignose+hates-spam at benfinney.id.au
Sat Feb 3 03:50:34 EST 2007


fatwallet961 at yahoo.com writes:

> is the main function in python is exact compare to Java main method?
> all execution start in main which may takes arguments?

There's no such thing in Python; a module is executed sequentially,
with no particular regard to the names of any of the attributes.

There is, though, a convention of writing a module that can be either
imported or executed as a program, by testing inside the module
whether the current module name is the magic string "__main__".

=== foo.py ===
# This code is executed whether or not this module is the main module
print "Module foo.py is running with name:", __name__

if __name__ == '__main__':
    # This block is executed only if the module is the main program module
    print "Module foo.py is the main program"
=== foo.py ===

=== bar.py ===
import foo

print "Module bar.py is running with name:", __name__
=== bar.py ===

=====
$ python ./foo.py       # Run foo.py as a program
Module foo.py is running with name: __main__
Module foo.py is the main program

$ python ./bar.py       # Run bar.py as a program, which imports foo.py as a module
Module foo.py is running with name: foo
Module bar.py is running with name: __main__
=====

That allows the following idiom:

> if __name__ == "__main__":
>     sys.exit( main(sys.argv) )

All the rest of the code is executed whether or not the program is the
main module; but right at the end, after defining all the attributes
and functions and classes etc., this test says *if* this module is the
main program, then *also* execute the "main" function (and then exit
Python with the return value from that function).

The benefit of this is that this module, designed to be run as a
program, is *also* designed to be imported by other programs so that
its functions etc. can be used as required, *without* necessarily
running the main function.

-- 
 \      "If I haven't seen as far as others, it is because giants were |
  `\                        standing on my shoulders."  -- Hal Abelson |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list