经常一知半解,故整理下,方便后续回顾。
首先:Python 属于脚本语言,不像编译型语言那样先将程序编译成二进制再运行,而是动态的逐行解释运行。也就是从脚本第一行开始运行,没有统一的入口。
对于下面这段代码:
# 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")
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 two.py
func() in one.py
two.py is being run directly
因此,采用这种方式编辑的one.py可以选择性的运行某些行。
另有文章“http://blog.konghy.cn/2017/04/24/python-entry-program/” 写的也比较详细,需要的时候可以细看。