main in Python

T

Tim

Hi,
I learned that a Python script is written in this way:
def main():
...
if __name__ == "__main__":
main()

Today, when I read a script, I found it has a different way:

def main():
...

main()

It can run as well. Can someone explain why and the rules that Python scripts get run?

Thanks and regards,
Tim
 
T

Tim Harig

On 2009-07-10 said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,161
Latest member
GertrudeMa
Top