In many Python modules you can find construction like:
if __name__ == "__main__": func()
Its main purpose is to dedicate a code which will be executed during calling code as a module, after importing it into another code – and when running module itself as a dedicated script.
Note: this post initially was written on 09/12/2014 in my Russian blog version so here is Python 2 used.
Let’s take a look at a couple of examples.
Script 1 :
#!/usr/bin/env python
print('Script 1. My name is: %s' % __name__)
print('This is simple code from script 1')
def func():
print('This is code from function from script 1')
if __name__ == "__main__":
func()
And Script 2 :
#!/usr/bin/env python
print('Script2. My name is: %s' % __name__)
print('Importing ifname1')
import ifname1
The execution result of the Script 2 directly:
$ ./ifname2.py
Script2. My name is: __main__
Importing ifname1
Script 1. My name is: ifname1
This is simple code from script 1
The execution result of the Script 1 directly:
$ ./ifname1.py
Script 1. My name is: __main__
This is simple code from script 1
This is code from function from script 1
Another example.
Script 1 :
#!/usr/bin/env python
if __name__ == "__main__":
print('I am running as an independent program with name = %s' % __name__)
else:
print('I am running as an imported module with name = %s' % __name__)
And Script 2 – no changes here:
#!/usr/bin/env python
print('Script2. My name is: %s' % __name__)
print('Importing ifname1')
import ifname1
Executing the Script 2 will give us the next result:
$ ./ifname2.py
Script2. My name is: __main__
Importing ifname1
I am running as an imported module with name = ifname1
While running the Script 1 – next:
$ ./ifname1.py
I am running as an independent program with name = __main__
Similar posts
- 03/16/2018 Python: pip – AttributeError: ‘module’ object has no attribute ‘SSL_ST_INIT’ (0)
- 12/31/2017 Python: boto3 и скрипт обновления AWS Security Group (0)
- 02/26/2015 Python: PyLint – поиск ошибок и анализ качества кода (0)
- 01/02/2018 Python: boto3 – примеры авторизации (0)
Top comments (0)