Python 2.x.x 中的模块导入
Module import in Python 2.x.x
我想将我以前的程序用作模块。但是当我导入那个程序时,自动编程 运行s。我不想运行程序。我只想将该程序作为一个模块导入到我的新程序中,我使用该模块中的函数或变量。我试图添加这一行 if __name__ == "__main__"
。但它也没有用。我怎样才能阻止此操作?(我正在使用 python2.x.x)
if __name__ == "__main__"
中的代码仅当您直接 运行 执行该程序时才会执行,否则将被忽略。
其余代码一直执行。
组织代码的正确方法是在 if __name__ == "__main__"
之前声明每个属性(函数、常量、class...),然后将 运行 该程序。这是结构:
# 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()
我想将我以前的程序用作模块。但是当我导入那个程序时,自动编程 运行s。我不想运行程序。我只想将该程序作为一个模块导入到我的新程序中,我使用该模块中的函数或变量。我试图添加这一行 if __name__ == "__main__"
。但它也没有用。我怎样才能阻止此操作?(我正在使用 python2.x.x)
if __name__ == "__main__"
中的代码仅当您直接 运行 执行该程序时才会执行,否则将被忽略。
其余代码一直执行。
组织代码的正确方法是在 if __name__ == "__main__"
之前声明每个属性(函数、常量、class...),然后将 运行 该程序。这是结构:
# 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()