tf.app.run() 是如何工作的? [英] How does tf.app.run() work?
问题描述
tf.app.run()
在 Tensorflow 翻译演示中是如何工作的?
How does tf.app.run()
work in Tensorflow translate demo?
在tensorflow/models/rnn/translate/translate.py
中,有一个对tf.app.run()
的调用.是怎么处理的?
In tensorflow/models/rnn/translate/translate.py
, there is a call to tf.app.run()
. How is it being handled?
if __name__ == "__main__":
tf.app.run()
推荐答案
if __name__ == "__main__":
表示当前文件在shell下执行,而不是作为模块导入.
means current file is executed under a shell instead of imported as a module.
tf.app.run()
正如你通过文件app.py
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))
让我们逐行分解:
flags_passthrough = f._parse_flags(args=args)
这确保您通过命令行传递的参数是有效的,例如python my_model.py --data_dir='...' --max_iteration=10000
其实这个特性是基于python标准的argparse
模块实现的.
This ensures that the argument you pass through command line is valid,e.g.
python my_model.py --data_dir='...' --max_iteration=10000
Actually, this feature is implemented based on python standard argparse
module.
main = main or sys.modules['__main__'].main
=
右侧的第一个main
是当前函数的第一个参数run(main=None, argv=None)
.而 sys.modules['__main__']
表示当前正在运行的文件(例如 my_model.py
).
The first main
in right side of =
is the first argument of current function run(main=None, argv=None)
. While sys.modules['__main__']
means current running file(e.g. my_model.py
).
所以有两种情况:
你在
my_model.py
中没有main
函数那么你必须调用tf.app.run(my_main_running_function)
You don't have a
main
function inmy_model.py
Then you have to calltf.app.run(my_main_running_function)
您在 my_model.py
中有一个 main
函数.(主要是这种情况.)
you have a main
function in my_model.py
. (This is mostly the case.)
最后一行:
sys.exit(main(sys.argv[:1] + flags_passthrough))
确保您的 main(argv)
或 my_main_running_function(argv)
函数被正确解析参数调用.
ensures your main(argv)
or my_main_running_function(argv)
function is called with parsed arguments properly.
这篇关于tf.app.run() 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!