tensorflow中tf.app.run()的含义

来源:互联网 发布:软件数据接口 编辑:程序博客网 时间:2024/05/29 21:36

今天在学习 mnist 代码的时候,看到主函数中有如下的代码:

FLAGS, unparsed = parser.parse_known_args()tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

第一行的含义是对运行命令行时传进来的参数进行解析,如果传进来的参数是之前被add到parser中的,则被传给FLAGS,否则讲传给unpared。

如我们在运行程序时在后面加上了 --epoch 32 参数,如果这个参数之前被加入到parser中,则将parser中的epoch参数更改为32并传诶FLAGS,否则 则将 --epoch 32写入到unparsed中

为了了解第二行的含义,我们在/tensorflow/python/platform中找到app.py并打开。


# Copyright 2015 The TensorFlow Authors. All Rights Reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at##     http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# =============================================================================="""Generic entry point script."""from __future__ import absolute_importfrom __future__ import divisionfrom __future__ import print_functionimport sys as _sysfrom tensorflow.python.platform import flagsfrom tensorflow.python.util.all_util import remove_undocumenteddef _benchmark_tests_can_log_memory():  return Truedef 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))
我们给这个方法传递了两个参数,一个是要运行的主方法,另一个是:
argv=[sys.argv[0]] + unparsed
这个列表中储存了我们要运行的程序的位置,以及没有被parser匹配的参数。
help中写道run()方法的用途是用argv列表运行一个可选的main方法。

下面的语句将没有被parser匹配的参数放入args中并且通过一个flags对象传入要执行的函数中。

args = argv[1:] if argv else None
flags_passthrough = f._parse_flags(args=args)

如果我们传入了一个函数名,则程序会去用没有匹配的参数执行这个函数,否则,则会用没有匹配的参数去执行__main__。

main = main or _sys.modules['__main__'].main_sys.exit(main(_sys.argv[:1] + flags_passthrough))

原创粉丝点击