The code under if __name__ == '__main__':
will be executed only if the module is invoked as a script.
As an example consider the following module my_test_module.py
:
# my_test_module.py
print('This is going to be printed out, no matter what')
if __name__ == '__main__':
print('This is going to be printed out, only if user invokes the module as a script')
1st possibility: Import my_test_module.py
in another module
# main.py
import my_test_module
if __name__ == '__main__':
print('Hello from main.py')
Now if you invoke main.py
:
python main.py
>> 'This is going to be printed out, no matter what'
>> 'Hello from main.py'
Note that only the top-level print()
statement in my_test_module
is executed.
2nd possibility: Invoke my_test_module.py
as a script
Now if you run my_test_module.py
as a Python script, both print()
statements will be exectued:
python my_test_module.py
>>> 'This is going to be printed out, no matter what'
>>> 'This is going to be printed out, only if user invokes the module as a script'
For a more comprehensive explanation you can read this blog post.