Home >Backend Development >Python Tutorial >How to find the current module name in Python?
A module can find its own module name by looking at the predefined global variable __name__. If its value is "__main__", the program runs as a script.
def main(): print('Testing…...') ... if __name__ == '__main__': main()
Testing…...
Modules typically used via import also provide a command line interface or self-test, and this code is only executed after checking __name__.
__name__ is a built-in variable in the Python language. We can write a program to view the value of this variable. Here is an example. We will also check the type -
print(__name__) print(type(__name__))
__main__ <type 'str'>
Let’s see another example -
We have a file Demo.py.
def myFunc(): print('Value of __name__ = ' + __name__) if __name__ == '__main__': myFunc()
Value of __name__ = __main__
Now, we will create a new file Demo2.py. In this we have imported Demo and called the function from Demo.py.
import Demo as dm print('Running the imported script') dm.myFunc() print('\n') print('Running the current script') print('Value of __name__ = ' + __name__)
Running the imported script Value of __name__ = Demo Running the current script Value of __name__ = __main__
The above is the detailed content of How to find the current module name in Python?. For more information, please follow other related articles on the PHP Chinese website!