python官方手册:
‘__main__’ is the name of the scope in which top-level code executes. A module’s __name__ is set equal to ‘__main__’ when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
分析一下:
__main__就是最顶级代码的名字,而__name__是代码本身的名字。
通过判断二者是否相等,可以判断该代码是被imported还是直接执行的。
__file__
当前路径
print(__name__) #如果是主文件, __name__ = "__main__" ,否则等于模块名
print(__doc__) #没有则为None
print(__file__) #指当前文件路径 配合os.path.dirname 使用比例大