Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1778511
  • 博文数量: 276
  • 博客积分: 1574
  • 博客等级: 上尉
  • 技术积分: 2894
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-26 23:23
个人简介

生活的美妙在于,不知道一下秒是惊艳还是伤神,时光流转,珍惜现在的拥有的时光

文章分类

全部博文(276)

文章存档

2017年(17)

2016年(131)

2015年(63)

2013年(2)

2012年(32)

2011年(31)

分类: Python/Ruby

2016-05-05 14:37:07

在saltstack原码salt-2015.8.8.2/salt/version.py中

点击(此处)折叠或打开

  1. if __name__ == '__main__':
  2.     print(__version__)
经常有程序这样写:

点击(此处)折叠或打开

  1. def main():
  2.     ......
  3.  
  4. if __name == "__main__":
  5.     main();


顺便学习了一下__name__


在模块中直接使用,__name__是__main__;
在模块中导入模块,__name__是模块名;
在类中使用,__name__是类名.

Modules…

Predefined (writable) attributes: __name__ is the module’s name;

… Classes…

Special attributes: __name__ is the class name;

29.4.  — Top-level script environment

'__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() 

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.




t@localhost python$ cat namemethod.py 
#!/usr/bin/env python3
def tprint():
    print('__name__ is %s' %(__name__))
if __name__ == '__main__':
    tprint()
else:
    print('import:')
    tprint()
t@localhost python$ ./namemethod.py 
__name__ is __main__
t@localhost python$ cat test.py 
#!/usr/bin/env python3
mport namemethod
tprint()
t@localhost python$ ./test.py 
import:
__name__ is namemethod
__name__ is namemethod




阅读(905) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~