Python's equivalent to Main calling program and subprograms

Benjamin Kaplan benjamin.kaplan at case.edu
Wed Dec 1 12:24:18 EST 2010


On Wed, Dec 1, 2010 at 12:08 PM, m b <snert at hotmail.se> wrote:
>
>
>> >
>> > if __name__ == "__main__":
>> > main()
>
> What does this mean?
>
> /Mikael
>

Every module has an attribute called __name__. Normally, it's the name
of the module itself. However, the module being run as a script
(rather than imported) is called __main__. You can use if __name__ ==
"__main__" to have certain things only run if the file is executed
directly.

---- a.py ----
print "I'm A"
if __name__ == '__main__' :
    print "I'm the main script"

--- b.py ---
import a

$ python a.py
I'm A
I'm the main script
$ python b.py
I'm A



More information about the Python-list mailing list