Python 2.x.x中的模块导入

时间:2017-03-22 21:37:51

标签: python python-2.7 python-import python-2.6 python-module

我想将以前的程序用作模块。但是当我导入该程序时,程序会自动运行。我不想运行程序。我只想将该程序导入到我的新程序中作为我使用该模块中的函数或变量的模块。我尝试添加此行if __name__ == "__main__"。但它也没有用。如何阻止此操作?(我使用的是python2.x.x)

1 个答案:

答案 0 :(得分:0)

if __name__ == "__main__"中的代码仅在您直接运行该程序时执行,否则将被忽略 其余的代码一直在执行。

组织代码的正确方法是在if __name__ == "__main__"之前声明每个属性(函数,常量,类......),然后放置运行程序的代码。结构如下:

# only "passive" code until the __name__=="__main__"

# could be importation...
import sys

# ...global variables
version = 42

# ...or functions
def foo(x):
    print("foo called")

def bar(x):
    print("bar called")
    return x + 1

if __name__ == "__main__":
    # start the effective code here

    print("program running")
    print("version :", version)
    foo()
    n = bar(2)
    print(n)

您还可以定义一个在末尾调用的函数

...

def main():
    print("program running")
    print("version :", version)
    foo()
    n = bar(2)
    print(n)

if __name__ == "__main__":
    main()
相关问题