Home  >  Article  >  Backend Development  >  What does "if __name__ == __main__:" do?

What does "if __name__ == __main__:" do?

anonymity
anonymityOriginal
2019-05-24 14:43:1813773browse

The role of "if __name__ == __main__:": specifies the main method function. The main function is started when the script is executed, but will not be executed when other files are imported.

What does

There are two ways to use a python file. The first is to execute it directly as a script, and the second is to be imported in the python script of other files. Call (module reuse) execution. Therefore, the function of if name == 'main': is to control the process of executing the code in these two situations. The code under if name == 'main': can only be executed in the first situation (that is, the file is directly executed as a script). will be executed, but importing it into other scripts will not be executed.

Example:

# file one.pydef func():
    print("func() in one.py")
print("top-level in one.py")if __name__ == "__main__":
    print("one.py is being run directly")else:
    print("one.py is being imported into another module")
# file two.pyimport one        # start executing one.pyprint("top-level in two.py")
one.func()if __name__ == "__main__":
    print("two.py is being run directly")else:
    print("two.py is being imported into another module")

When running python one.py, the output is:

top-level in one.py
one.py is being run directly

When running python two.py, the output is:

top-level in one.py
one.py is being imported into another module
top-level in one.pyfunc() in one.py
two.py is being run directly

The above is the detailed content of What does "if __name__ == __main__:" do?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn