__name__ of a fileWhen python interpreter run a script, the script will have several variable that not defined purposely by the user, now the special variable we will talk about is __name__
For example, here are two simple files for illustration: test.py ------------------------------------------------------------- #!/usr/bin/python if __name__ == '__main__': print 'run directly, so the __name__ is main' else: print 'not run directly, but called by others, and name is', __name__ def printFunction(): if __name__ == '__main__': print 'run directly, so the __name__ is main' else: print 'not run directly, but called by others, and name is', __name__ return ------------------------------------------------------------- And others.py ------------------------------------------------------------- from test import printFunction printFunction() ------------------------------------------------------------- Now, if one runs the test.py directly by directly execute the code using python test.py The script is directly run by interpreter so the __name__ is __main__, then output will be 'run directly, so the __name__ is main' if run python others.py 'not run directly, but called by others, and name is test' 'not run directly, but called by others, and name is test' Conclusion: 1. if python directly call a source file, the __name__ in that source file would be "__main__" 2. if python indirectly call a source file, the __name__ in that source file will be the name of the file without extension .py |
AuthorShaowu Pan Archives
December 2017
Categories
All
|