美文网首页
Python __main__的作用

Python __main__的作用

作者: Albert新荣 | 来源:发表于2019-04-14 01:02 被阅读0次

    file one.py

    # 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

    # file two.py
    import one        # start executing one.py
    
    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")
    

    当运行python one.py,输出:

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

    当运行python two.py,输出:

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

    相关文章

      网友评论

          本文标题:Python __main__的作用

          本文链接:https://www.haomeiwen.com/subject/lrgdwqtx.html