Usage python in the main function

What will be the main function at the scene?

When the script is introduced into the python (Import) as a module (module), wherein the main () function will not be executed.

The main function of the role?

__ name__ == '__ main__' is the main function of the inlet Python. He not said, adding that the sentence can be carried out using python xxx.py, but that, where you can judge whether the current is directly python directly called.

Why only the main file as the implementation of the program will be executed when it?

This is due to two reasons, on the one hand, main function is the entry of all execution of the program; on the other hand, python interpreter is the order of execution of the script and does not call any code and functions that do not belong to the program itself, the need to add that is, if the module is used as a library or import into the program, it will directly become part of the code.

Reference Code:

File: main_function.py

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import datetime

print('Hello World!')
print('Time is ', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S %A'))


def main():
    print('this message is from main function')


if __name__ == '__main__':
    main()

Results of the:

➜  main git:(master) ✗ py main_function.py
Hello World!
Time is  2019-07-22 09:50:50 Monday
this message is from main function

II of document: test_main.py

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import main_function

print("Done!")

Results of the:

➜  main git:(master) ✗ py test_main.py
Hello World!
Time is  2019-07-22 09:52:00 Monday
Done!
Published 705 original articles · won praise 829 · Views 1.32 million +

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/105139803