python 之 if __name__ == '__main__': 和 tf.app.run()

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__'结果为真。

#主函数的入口,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

           http://www.dengfeilong.com/post/60.html

猜你喜欢

转载自blog.csdn.net/weixin_42338058/article/details/84107414