tf.app.flags
用来解析命令行参数,类似 python 自带的 argparser。用 tf.app.flags.DEFINE_*
定义参数名、默认值、帮助信息,最终结果会放在 tf.app.flags.FLAGS
里。不依赖于 tf.app.run()
的调用,单独用 tf.app.flags
就可以解析。
不过由其代码[2]看,似乎只能传 int、float、bool、string 四种类型,传不了 list,而 argparser 可以。传 bool 参数时只能用 =
隔开参数名和参数值,而其它 3 种类型可以用 =
或空格,见下文例子。
用 tf.app.run()
时,要定义 main(args)
函数,它会自动调 main
,并简单地把命令行参数(调用时空格隔开的若干字符串)作为参数传给 main
,好像并没有什么卵用。
Code
- tensorflow 1.12
tf.app.flags
# test.py
import tensorflow as tf
# 参数名,默认值,帮助信息
tf.app.flags.DEFINE_integer('batch_size', 64, "batch size")
tf.app.flags.DEFINE_float('alpha', 0.5, "alpha")
tf.app.flags.DEFINE_boolean('save', True, "whether to save the results")
tf.app.flags.DEFINE_string('log_path', 'log', "log path")
FLAGS = tf.app.flags.FLAGS
if "__main__" == __name__:
print("\n--- FLAGS ---")
print(FLAGS)
print("\n--- FLAGS.__flags ---")
print(FLAGS.__flags)
print("\n--- enum ---")
for k in FLAGS:
print(k)
print("\n--- fields ---")
print("batch size:", FLAGS.batch_size)
print("alpha:", FLAGS.alpha)
print("save:", FLAGS.save)
print("log path:", FLAGS.log_path)
- 调用例子
python test.py
python test.py --batch_size 1 # 可以空格
python test.py --alpha=0.1 # 也可以 `=`
python test.py --save=False # 只能 `=`
python test.py --save False # **没**有效果
tf.app.run
# test.py
import tensorflow as tf
def main(cmd_line_args):
print("--- command line arguments ---")
print(cmd_line_args)
if "__main__" == __name__:
# this will parse the command line arguments
# and call `main` functions automatically
tf.app.run()
- 调用例子
python test.py
# 输出:['test.py']
python test.py --batch_size 1
# 输出:['test.py', '--batch_size', '1']
python test.py --batch_size=1 --alpha 0.1
# 输出:['test.py', '--batch_size=1', '--alpha', '0.1']