main in Python

Tim Harig usernet at ilthio.net
Fri Jul 10 18:13:00 EDT 2009


On 2009-07-10, Tim <timlee126 at yahoo.com> wrote:
[RE-ORDERED]
> It can run as well. Can someone explain why and the rules that Python
> scripts get run?

Everything gets run by default.  The def syntax defines functions but does
not run them -- they are only run when they are called

> Today, when I read a script, I found it has a different way:
> def main():
>     ...
>
> main()

This define main and then runs it.

> def main():
>     ...
> if __name__ == "__main__":
>     main()

This defines main but it only runs it if __name__ == "__main" which will
only happen if the script is called directly:

./sample.py
or
python sample.py
etc.

This form is often preferred because it allows you to import definitions
the module without running the code within the main funciton module.
That way the same file can be used as a standalone program or as an
importable module.



More information about the Python-list mailing list