这是否有更短的形式?
if __name__ == '__main__':
Run Code Online (Sandbox Code Playgroud)
写作非常繁琐,而且在我看来也不是很好看:)
Mat*_*tis 12
PEP299提出了这种疣的解决方案,即具有特殊的功能名称__main__.它遭到拒绝,部分原因是:
Guido宣称他不喜欢这个想法,因为它"不值得改变(在文档,用户习惯等方面)并且没有什么特别破坏."
http://www.python.org/dev/peps/pep-0299/
所以丑陋会留下来,至少和Guido的BDFL一样长.
基本上每个python程序员都这样做.所以简单地忍受吧.;)
除此之外,如果你的脚本总是作为一个应用程序运行而不是作为一个模块导入,你可以完全省略它 - 但你仍然鼓励你使用它,即使它不是真的有必要.
在提出这个问题之后,我决定为它做一个解决方案:
from automain import * # will only import the automain decorator
@automain
def mymain():
print 'this is our main function'
Run Code Online (Sandbox Code Playgroud)
该博客文章解释了它,和代码在GitHub上,可以easy_installed:
easy_install automain
Run Code Online (Sandbox Code Playgroud)