Flow of execution in Python

This question already has an answer here:

  • What does if __name__ == “__main__”: do? 23 answers

  • The Python interpreter knows nothing of a main() function - the flow is just line by line.

    The block that goes:

    if __name__ =="__main__": main()
    

    is a explicit call to a function if the magic variable __name__ contains the string "__main__" . That thing, the content of __name__ is the one special thing the Python runtime does when running a module: if the current module is the main program that was invoked, it contains the string __main__ , otherwise its contents are rather the module name.

    So, if you want your main function (which can have whatever name) placed in another file, you can just import it at invocation time:

    if __name__ =="__main__": 
         from other_module import main 
         main()
    

    This feature is interesting as it allows any Python file to work both as a loadable library module by other programs, and offer standalone functionality as a program.

    However, for a Python package, that is, a folder containing related .py files, that each correspond to a module, Python has to choose which of these modules is run sequentially. When you execute a package using the -m directive to the Python runtime, it findes a file named __main__.py inside the package and executes that one - in the absence of such a file, the package cannot be run directly.

    Follwing the same line of though, the __main__.py file is only run automatically when executing the package as the main program - if the package, or parts of it, are imported by another program, it is not executed. That, unlike checking the contents of __name__ with an if expression is actually a built-in behavior that defines a starting-place.


    When you run a single Python script from the command-line with python script.py , interpretation starts at the first line and continues line by line. If a line starts a class or function definition, the definition is stored for later reference. If the line is executable code, it is directly executed. In the case of the statement if __name__ == "__main__": main() , this is directly executable, if the condition evaluates to true then main() is called. However, this isn't special. You can have whatever code you wish in the if body.

    链接地址: http://www.djcxy.com/p/9320.html

    上一篇: 如何在unix中运行python函数?

    下一篇: Python中的执行流程