The if __name__ == "__main__": main()
condition checks if you are running the script via python interpreter and calls the main()
function. For more detailed explanation refer to this question What does if name == “main”: do?
If you have a program like this
# script.py
def hello_world():
print "Hello World!"
hello_world()
if __name__ == "__main__":
main()
Hello World!
would be printed whether you import script.py
or run it from command line like python script.py
, because the function hello_world()
is executed in both instances.
Case 1: Running from command line
$ python script.py
Hello World!
Traceback (most recent call last):
File "/path/to/tests/script.py", line 8, in <module>
main()
NameError: name 'main' is not defined
Case 2: Importing as module
>>> import script
Hello World!
If you want to stop it from being printed, then wrap the executing part of the code in the main function like this:
def hello_world():
print "Hello World!"
def main():
hello_world()
if __name__ == "__main__":
main()
Now, hello_world()
gets called (or Hello World!
gets printed) only when you run it as a script and not when you import it as a module.