使用tensorflow.app.run(main) 调用main函数的时候,报了一个这样的错误
File "C:\Users\think\Anaconda3\lib\site-packages\tensorflow\python\platform\app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
TypeError: main() takes 0 positional arguments but 1 was given
查看源码文件
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))
最后一行
sys.exit(main(sys.argv[:1] + flags_passthrough))
这里将参数传给main
函数,需要注意的是,即使我们没有手动给命令行参数,因为将文件名argv[0]
传了过去,所以main
函数中需要写参数,不然就会有如上错误。
flags_passthrough = f._parse_flags(args=args)
这行确保了通过命令行传递的参数是有效的,实际上这也是基于标准的argparse模块实现的。
main = main or sys.modules['__main__'].main
等号第一个main
指的就是代码中的main函数,sys.modules['__main__'].main
指的是if __name__=='__main__'
下面的main函数,如果你定义了的话。
所以有两种情况:
1. 你没有定义main
函数,你需要指定函数运行tf.app.run(my_main_running_function)
2. 你有main
函数