python文件有两种使用的方法:
1、直接作为脚本执行,
这时一般用来测试程序
2、import到其他的python脚本中被调用(模块重用)执行。
if __name__ == '__main__': 的作用就是控制这两种情况执行代码的过程,在 if __name__ == 'main': 下的代码只有在第一种情况下(即文件作为脚本直接执行)才会被执行,而import到其他脚本中是不会被执行的。
每个python模块(python文件)都包含内置的变量__name__,
当运行模块被直接执行的时候,__name__等于文件名即__main__(包含了后缀.py);
如果import到其他模块中,则__name__等于模块名称(不包含后缀.py)。
而“__main__”等于当前执行文件的名称(包含了后缀.py),进而当模块被直接执行时,__name__ == '__main__'结果为真。
tf.app.flags.DEFINE_xxx()就是添加命令行的optional argument(可选参数),
而tf.app.flags.FLAGS可以从对应的命令行参数取出参数
tf.app.flags可以在变量传入时赋值,普通方式的参数只能修改源码
#主函数的入口,import到其他脚本中,tf.app.run()不会运行
if __name__ == '__main__':
tf.app.run()
#如果你的代码中的入口函数不叫main(),而是一个其他名字的函数,如test(),则写tf.app.run(test())
#如果你的代码中的入口函数叫main(),则你就可以把入口写成tf.app.run()
#源代码
"""Generic entry point script."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from tensorflow.python.platform import flags
def run(main=None, argv=None):
"""Runs the program with an optional 'main' function and 'argv' list."""
f = flags.FLAGS
# Extract the args from the optional `argv` list.
args = argv[1:] if argv else None
# Parse the known flags from that list, or from the command
# line otherwise.
# pylint: disable=protected-access
flags_passthrough = f._parse_flags(args=args)
# pylint: enable=protected-access
main = main or sys.modules['__main__'].main
# Call the main function, passing through any arguments
# to the final program.
sys.exit(main(sys.argv[:1] + flags_passthrough))
欢迎批斗~~~
参考:https://blog.csdn.net/helei001/article/details/51859423