main in Python

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Jul 10 21:25:19 EDT 2009


On Fri, Jul 10, 2009 at 5:52 PM, Tim<timlee126 at yahoo.com> wrote:
>
> 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?
>


You're thinking like a C or Java programmer. Python scripts are just
that - scripts. They aren't compiled with a main() method for an entry
point- it's interpreted. When you run a python script, everything that
isn't indented is run, from top to bottom, in order. So for instance,
when the interpreter sees the line
def main() :
   pass
it creates a function called main. If you were to have the statement
x= 5
the value 5 would be assigned to x at that time. There are two ways to
execute these scripts- by running them directly and by importing them
into another module. The second way, with the main method, the script
will be run any time it is imported. The first relies on the fact that
any module run as a script has a __name__ attribute of "__main__"
(usually it's the name of the module). The first program acts more
like the C code would- the "main" part of it will only be run if that
script is executed.


> Thanks and regards,
> Tim
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list