python __main__ __name__ __file__

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 使用比例大
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值