• python if __name__ == '__main__' 作用


    转载:https://stackoverflow.com/questions/419163/what-does-if-name-main-do

    When your script is run by passing it as a command to the Python interpreter,

    python myscript.py

    all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no main()function that gets run automatically - the main() function is implicitly all the code at the top level.

    In this case, the top-level code is an if block. __name__ is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in myscript.pyabove), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

    if __name__ == "__main__":
        ...

    If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won't get run as the condition is not met. As a basic example, consider the following two scripts:

    # file one.py
    def 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.py
    import one
    
    print("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")

    Now, if you invoke the interpreter as

    python one.py

    The output will be

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

    If you run two.py instead:

    python two.py

    You get

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

    Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.

  • 相关阅读:
    2018-2019-2 20189212 《网络攻防技术》第一周作业
    2017、5、4
    Pyinstaller 打包exe 报错 "failed to execute script XXX"的一种解决方案
    解决 Onenote 默认全角输入的一种解决办法(输入法已经设置为默认半角)
    OneDrive一直后台占用CPU的一种解决办法
    etimer
    简单三层BP神经网络学习算法的推导
    win10无法设置移动热点的一种解决办法
    如何恢复误删的OneNote页面
    安装mysql遇到的坑--->Can't connect to MySQL server on 'localhost' (10061)
  • 原文地址:https://www.cnblogs.com/huahuayu/p/8335132.html
Copyright © 2020-2023  润新知