ModuleNotFoundError: No module named '__main__.base'; '__main__' is not a package(即 if __name__=='__main__'的深入理解)

if __name__ == '__main__': a brief description:

 

    Each module or python python file (hello1.py file in the figure below, and the difference between python module python --python files that have a file extension .py) includes built in the __name__ variable, but always refers to the current execution __main__ file or the current path. When the file is executed directly, __ name__ equal to the file name is equal __main__, __name__ at a time will be automatically assigned to parser "__main__", string type (Note that the value will not be __name__ assigned to tt.hello1.py, see Figure 1) , so that the expression if __name __ == "__ main__" is true. Next, look at FIG. 2, if the module (i.e. tt.hello1) is import  to other modules, the module is equal __name__ module name ( not included suffix .py), i.e., the value at this time __name__ tt.hello1 (Figure 2) .

    A python files typically used in two ways, first as a script is executed directly, and the second is to import another python script is called (block reuse) performed. Thus if __name__ == '__main__': role is to control execution of the code in both cases of the process. 1, FIG. 2, if __name__ == '__main__': only the code in the first case (i.e., as a script file directly performed) will be executed, and to import another script is not executed (because at this time __name __ = tt.hello1, expression if __name __ == "__ main__" is false ).

 

             

 

 

 

            

 

 

 

       Then analyze why being given ModuleNotFoundError: No module named '. __Main __ base'; '__main__' is not a package, shown in Figure 3

           

 

 

 

            FIG using a relative path, found import fails, .hello1 i.e. the current path module hello1

           At this time it is parsed into .hello1 __main __. Hello, causing the program to fail, to use an absolute path

           

 

Guess you like

Origin www.cnblogs.com/xiaohaodeboke/p/12587018.html