首页 > 编程知识 正文

python定义main函数,python调用main函数

时间:2023-05-05 20:29:07 阅读:184164 作者:1096

python 中name == ‘__main__’ 的作用

经典的英文解释:Make a script both importable and executable
中文解释:使脚本可以被调用import并且也可以直接运行

1、直接运行

# cat test_fun.pydef fun(): print(__name__) print('this is fun')if __name__ == '__main__': fun() print('this is main') python test_fun.py__main__this is funthis is main

2、被调用import

>>> import test_fun>>> test_fun.fun()test_funthis is fun

调用导入时:此处输出没有显示”main“,也就是说模块name = ‘main’ 下面的代码并未执行,main函数没有执行。

这个功能还有一个用处:调试代码的时候,在”if name == ‘main‘“中加入一些我们的调试代码,我们可以让外部模块调用的时候不执行我们的调试代码,但是如果我们想排查问题的时候,直接执行该模块文件,调试代码能够正常运行!

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。