Python 关于 name main的使用 if __name__ == '__main__':
来源:互联网 发布:万网域名赎回费用 编辑:程序博客网 时间:2024/05/29 04:48
看过很多python的code都有这段代码:
if
__name__
=
=
'__main__'
:
statements
这段代码的主要作用主要是让该python文件既可以独立运行,也可以当做模块导入到其他文件。当导入到其他的脚本文件的时候,此时__name__的名字其实是导入模块的名字,不是'__main__', main代码里面的就不执行了。
比如有这样的一个文件test.py, 里面代码如下:
# test.py
def
test():
print
(
"Test function."
)
if
__name__
=
=
'__main__'
:
test()
当按F5的时候可以独立运行程序,结果:
>>>
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
RESTART
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
>>>
Test function.<br>>>>
print
(__name__)<br>__main__<br>>>>
但是也可以作为模块import使用,结果:
>>>
import
test
>>> test.test
<function test at
0x0000000003455F28
>
>>> test.test()
Test function.
参考:
http://pyfaq.infogami.com/tutor-what-is-if-name-main-for
The if __name__ == "__main__": ...
trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. As a toy example, let's say that we have two files:
mumak:~ dyoo$ cat mymath.py
mymath.py文件
def
square(x):
return
x
*
x
if
__name__
=
=
'__main__'
:
print
"test: square(42) =="
, square(
42
)
mumak:~ dyoo$ cat mygame.py
mygame.py 文件
import
mymath
print
"this is mygame."
print
mymath.square(
17
)
In this example, we've written mymath.py to be both used as a utility module, as well as a standalone program. We can run mymath standalone by doing this:
mumak:~ dyoo$ python mymath.pytest: square(42) == 1764
But we can also use mymath.py as a module; let's see what happens when we run mygame.py:
mumak:~ dyoo$ python mygame.pythis is mygame.289
Notice that here we don't see the 'test' line that mymath.py had near the bottom of its code. That's because, in this context, mymath is not the main program. That's what the if __name__ == "__main__": ...
trick is used for.
在这个例子里面mygame.py里面调用square函数的时候,就不会执行mymath.py里面的main函数了。
- Python 关于 name main的使用 if __name__ == '__main__':
- python 关于 if __name__ == “__main__" 的使用
- 关于Python中 if __name__ = '__main__'
- 关于python中if __name__=='__main__'的含义
- 关于python中的 if __name__=='__main__': 的作用
- python if __name__ = '__main__'
- 关于python的 __name__== "__main__"
- 关于python函数中的if __name__ =="__main__"语句
- 【Python学习笔记】关于if __name__ == '__main__'
- 关于python中的if __name__==‘__main__’:
- Python 中的name 及__name__="__main__"
- 【Python】if __name__ == '__main__'
- 【Python】if __name__ == '__main__'
- python中if __name__ == '__main__':
- Python: if __name__ == "__main__"
- Python 之 if __name__ == '__main__':
- python if __name__ == '__main__' 详解
- 【Python】if __name__ == "__main__":
- Rotate Image 二维数组旋转90度
- 深度学习原理和实践
- 算法面试——二叉树最低公共祖先LCA
- 多线程和多进程的区别(小结)
- Anagrams 寻找相同的乱序的字母排列
- Python 关于 name main的使用 if __name__ == '__main__':
- 显示遮罩层并从屏幕上方滑出div
- oracle数据库导入与导出
- 【安全健行】(一):Hacker编程技能
- 2015.4.10学习mybatis
- 斯坦福大学机器学习第四课“逻辑回归(Logistic Regression)”
- Pow(x, n)
- 黑马程序员---JAVA中成员变量初始化规则
- PHP调用webservice的用法