1. 程式人生 > >python基礎 ——tf.app.run()

python基礎 ——tf.app.run()

python基礎

How does “tf.app.run()” work?

在這裡插入圖片描述

answer

  1. define your flags like tf.flags.DEFINE_integer(‘batch_size’, 128, ‘Number of images to process in a batch.’) and tf.app.run() will set things up so that you can globally
    access the passed values of the flags you defined, like tf.flags.FLAGS.batch_size from wherever you need it in your code.
  2. then run your custom main function with a set of arguments.

if name == “main”:

current file is executed under a shell instead of imported as a module.

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) # ensures that the argument you pass through command line is valid # pylint: enable=protected-access main = main or sys.modules['__main__'].main # The first main in right side of '=' :the first argument of current function run(main=None, argv=None); sys.modules['__main__'] :current running file(e.g.my_model.py). # Call the main function, passing through any arguments # to the final program. sys.exit(main(sys.argv[:1] + flags_passthrough)) # ensures your 'main(argv)' or 'my_main_running_function(argv)' function is called with parsed arguments properly

cases

  1. You don’t have a main function in my_model.py, Then you have to call tf.app.run(my_main_running_function) .
    if there’s no main in the file, it instead uses whatever’s in sys.modules[‘main’].main. The sys.exit : to run the main command thus found using the args and any flags passed through, and to exit with the return value of main.
  2. you have a main function inyou have a main function in
    my_model.py. (This is mostly the case.)